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/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/DominatorInternals.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/ProfileInfo.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/Constants.h"
27 #include "llvm/DataLayout.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Function.h"
30 #include "llvm/IRBuilder.h"
31 #include "llvm/InlineAsm.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/IntrinsicInst.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/PatternMatch.h"
40 #include "llvm/Support/ValueHandle.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetLibraryInfo.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/BuildLibCalls.h"
47 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
48 #include "llvm/Transforms/Utils/Local.h"
50 using namespace llvm::PatternMatch;
52 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
53 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
55 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
57 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
59 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
61 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
64 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
65 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
67 static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
71 static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
76 class CodeGenPrepare : public FunctionPass {
77 /// TLI - Keep a pointer of a TargetLowering to consult for determining
78 /// transformation profitability.
79 const TargetLowering *TLI;
80 const TargetLibraryInfo *TLInfo;
84 /// CurInstIterator - As we scan instructions optimizing them, this is the
85 /// next instruction to optimize. Xforms that can invalidate this should
87 BasicBlock::iterator CurInstIterator;
89 /// Keeps track of non-local addresses that have been sunk into a block.
90 /// This allows us to avoid inserting duplicate code for blocks with
91 /// multiple load/stores of the same address.
92 DenseMap<Value*, Value*> SunkAddrs;
94 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
98 /// OptSize - True if optimizing for size.
102 static char ID; // Pass identification, replacement for typeid
103 explicit CodeGenPrepare(const TargetLowering *tli = 0)
104 : FunctionPass(ID), TLI(tli) {
105 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
107 bool runOnFunction(Function &F);
109 const char *getPassName() const { return "CodeGen Prepare"; }
111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
112 AU.addPreserved<DominatorTree>();
113 AU.addPreserved<ProfileInfo>();
114 AU.addRequired<TargetLibraryInfo>();
118 bool EliminateFallThrough(Function &F);
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(BasicBlock *BB);
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.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
154 Attribute::OptimizeForSize);
156 /// This optimization identifies DIV instructions that can be
157 /// profitably bypassed and carried out with a shorter, faster divide.
158 if (TLI && TLI->isSlowDivBypassed()) {
159 const DenseMap<unsigned int, unsigned int> &BypassWidths =
160 TLI->getBypassSlowDivWidths();
161 for (Function::iterator I = F.begin(); I != F.end(); I++)
162 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
165 // Eliminate blocks that contain only PHI nodes and an
166 // unconditional branch.
167 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
169 // llvm.dbg.value is far away from the value then iSel may not be able
170 // handle it properly. iSel will drop llvm.dbg.value if it can not
171 // find a node corresponding to the value.
172 EverMadeChange |= PlaceDbgValues(F);
174 bool MadeChange = true;
177 for (Function::iterator I = F.begin(); I != F.end(); ) {
178 BasicBlock *BB = I++;
179 MadeChange |= OptimizeBlock(*BB);
181 EverMadeChange |= MadeChange;
186 if (!DisableBranchOpts) {
188 SmallPtrSet<BasicBlock*, 8> WorkList;
189 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
190 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
191 MadeChange |= ConstantFoldTerminator(BB, true);
192 if (!MadeChange) continue;
194 for (SmallVectorImpl<BasicBlock*>::iterator
195 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
196 if (pred_begin(*II) == pred_end(*II))
197 WorkList.insert(*II);
200 // Delete the dead blocks and any of their dead successors.
201 MadeChange |= !WorkList.empty();
202 while (!WorkList.empty()) {
203 BasicBlock *BB = *WorkList.begin();
205 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
209 for (SmallVectorImpl<BasicBlock*>::iterator
210 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
211 if (pred_begin(*II) == pred_end(*II))
212 WorkList.insert(*II);
215 // Merge pairs of basic blocks with unconditional branches, connected by
217 if (EverMadeChange || MadeChange)
218 MadeChange |= EliminateFallThrough(F);
222 EverMadeChange |= MadeChange;
225 if (ModifiedDT && DT)
226 DT->DT->recalculate(F);
228 return EverMadeChange;
231 /// EliminateFallThrough - Merge basic blocks which are connected
232 /// by a single edge, where one of the basic blocks has a single successor
233 /// pointing to the other basic block, which has a single predecessor.
234 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
235 bool Changed = false;
236 // Scan all of the blocks in the function, except for the entry block.
237 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
238 BasicBlock *BB = I++;
239 // If the destination block has a single pred, then this is a trivial
240 // edge, just collapse it.
241 BasicBlock *SinglePred = BB->getSinglePredecessor();
243 // Don't merge if BB's address is taken.
244 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
246 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
247 if (Term && !Term->isConditional()) {
249 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
250 // Remember if SinglePred was the entry block of the function.
251 // If so, we will need to move BB back to the entry position.
252 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
253 MergeBasicBlockIntoOnlyPred(BB, this);
255 if (isEntry && BB != &BB->getParent()->getEntryBlock())
256 BB->moveBefore(&BB->getParent()->getEntryBlock());
258 // We have erased a block. Update the iterator.
265 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
266 /// debug info directives, and an unconditional branch. Passes before isel
267 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
268 /// isel. Start by eliminating these blocks so we can split them the way we
270 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
271 bool MadeChange = false;
272 // Note that this intentionally skips the entry block.
273 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
274 BasicBlock *BB = I++;
276 // If this block doesn't end with an uncond branch, ignore it.
277 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
278 if (!BI || !BI->isUnconditional())
281 // If the instruction before the branch (skipping debug info) isn't a phi
282 // node, then other stuff is happening here.
283 BasicBlock::iterator BBI = BI;
284 if (BBI != BB->begin()) {
286 while (isa<DbgInfoIntrinsic>(BBI)) {
287 if (BBI == BB->begin())
291 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
295 // Do not break infinite loops.
296 BasicBlock *DestBB = BI->getSuccessor(0);
300 if (!CanMergeBlocks(BB, DestBB))
303 EliminateMostlyEmptyBlock(BB);
309 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
310 /// single uncond branch between them, and BB contains no other non-phi
312 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
313 const BasicBlock *DestBB) const {
314 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
315 // the successor. If there are more complex condition (e.g. preheaders),
316 // don't mess around with them.
317 BasicBlock::const_iterator BBI = BB->begin();
318 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
319 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
321 const Instruction *User = cast<Instruction>(*UI);
322 if (User->getParent() != DestBB || !isa<PHINode>(User))
324 // If User is inside DestBB block and it is a PHINode then check
325 // incoming value. If incoming value is not from BB then this is
326 // a complex condition (e.g. preheaders) we want to avoid here.
327 if (User->getParent() == DestBB) {
328 if (const PHINode *UPN = dyn_cast<PHINode>(User))
329 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
330 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
331 if (Insn && Insn->getParent() == BB &&
332 Insn->getParent() != UPN->getIncomingBlock(I))
339 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
340 // and DestBB may have conflicting incoming values for the block. If so, we
341 // can't merge the block.
342 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
343 if (!DestBBPN) return true; // no conflict.
345 // Collect the preds of BB.
346 SmallPtrSet<const BasicBlock*, 16> BBPreds;
347 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
348 // It is faster to get preds from a PHI than with pred_iterator.
349 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
350 BBPreds.insert(BBPN->getIncomingBlock(i));
352 BBPreds.insert(pred_begin(BB), pred_end(BB));
355 // Walk the preds of DestBB.
356 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
357 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
358 if (BBPreds.count(Pred)) { // Common predecessor?
359 BBI = DestBB->begin();
360 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
361 const Value *V1 = PN->getIncomingValueForBlock(Pred);
362 const Value *V2 = PN->getIncomingValueForBlock(BB);
364 // If V2 is a phi node in BB, look up what the mapped value will be.
365 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
366 if (V2PN->getParent() == BB)
367 V2 = V2PN->getIncomingValueForBlock(Pred);
369 // If there is a conflict, bail out.
370 if (V1 != V2) return false;
379 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
380 /// an unconditional branch in it.
381 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
382 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
383 BasicBlock *DestBB = BI->getSuccessor(0);
385 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
387 // If the destination block has a single pred, then this is a trivial edge,
389 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
390 if (SinglePred != DestBB) {
391 // Remember if SinglePred was the entry block of the function. If so, we
392 // will need to move BB back to the entry position.
393 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
394 MergeBasicBlockIntoOnlyPred(DestBB, this);
396 if (isEntry && BB != &BB->getParent()->getEntryBlock())
397 BB->moveBefore(&BB->getParent()->getEntryBlock());
399 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
404 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
405 // to handle the new incoming edges it is about to have.
407 for (BasicBlock::iterator BBI = DestBB->begin();
408 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
409 // Remove the incoming value for BB, and remember it.
410 Value *InVal = PN->removeIncomingValue(BB, false);
412 // Two options: either the InVal is a phi node defined in BB or it is some
413 // value that dominates BB.
414 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
415 if (InValPhi && InValPhi->getParent() == BB) {
416 // Add all of the input values of the input PHI as inputs of this phi.
417 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
418 PN->addIncoming(InValPhi->getIncomingValue(i),
419 InValPhi->getIncomingBlock(i));
421 // Otherwise, add one instance of the dominating value for each edge that
422 // we will be adding.
423 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
424 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
425 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
427 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
428 PN->addIncoming(InVal, *PI);
433 // The PHIs are now updated, change everything that refers to BB to use
434 // DestBB and remove BB.
435 BB->replaceAllUsesWith(DestBB);
436 if (DT && !ModifiedDT) {
437 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
438 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
439 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
440 DT->changeImmediateDominator(DestBB, NewIDom);
444 PFI->replaceAllUses(BB, DestBB);
445 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
447 BB->eraseFromParent();
450 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
453 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
454 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
455 /// sink it into user blocks to reduce the number of virtual
456 /// registers that must be created and coalesced.
458 /// Return true if any changes are made.
460 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
461 // If this is a noop copy,
462 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
463 EVT DstVT = TLI.getValueType(CI->getType());
465 // This is an fp<->int conversion?
466 if (SrcVT.isInteger() != DstVT.isInteger())
469 // If this is an extension, it will be a zero or sign extension, which
471 if (SrcVT.bitsLT(DstVT)) return false;
473 // If these values will be promoted, find out what they will be promoted
474 // to. This helps us consider truncates on PPC as noop copies when they
476 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
477 TargetLowering::TypePromoteInteger)
478 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
479 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
480 TargetLowering::TypePromoteInteger)
481 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
483 // If, after promotion, these are the same types, this is a noop copy.
487 BasicBlock *DefBB = CI->getParent();
489 /// InsertedCasts - Only insert a cast in each block once.
490 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
492 bool MadeChange = false;
493 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
495 Use &TheUse = UI.getUse();
496 Instruction *User = cast<Instruction>(*UI);
498 // Figure out which BB this cast is used in. For PHI's this is the
499 // appropriate predecessor block.
500 BasicBlock *UserBB = User->getParent();
501 if (PHINode *PN = dyn_cast<PHINode>(User)) {
502 UserBB = PN->getIncomingBlock(UI);
505 // Preincrement use iterator so we don't invalidate it.
508 // If this user is in the same block as the cast, don't change the cast.
509 if (UserBB == DefBB) continue;
511 // If we have already inserted a cast into this block, use it.
512 CastInst *&InsertedCast = InsertedCasts[UserBB];
515 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
517 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
522 // Replace a use of the cast with a use of the new cast.
523 TheUse = InsertedCast;
527 // If we removed all uses, nuke the cast.
528 if (CI->use_empty()) {
529 CI->eraseFromParent();
536 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
537 /// the number of virtual registers that must be created and coalesced. This is
538 /// a clear win except on targets with multiple condition code registers
539 /// (PowerPC), where it might lose; some adjustment may be wanted there.
541 /// Return true if any changes are made.
542 static bool OptimizeCmpExpression(CmpInst *CI) {
543 BasicBlock *DefBB = CI->getParent();
545 /// InsertedCmp - Only insert a cmp in each block once.
546 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
548 bool MadeChange = false;
549 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
551 Use &TheUse = UI.getUse();
552 Instruction *User = cast<Instruction>(*UI);
554 // Preincrement use iterator so we don't invalidate it.
557 // Don't bother for PHI nodes.
558 if (isa<PHINode>(User))
561 // Figure out which BB this cmp is used in.
562 BasicBlock *UserBB = User->getParent();
564 // If this user is in the same block as the cmp, don't change the cmp.
565 if (UserBB == DefBB) continue;
567 // If we have already inserted a cmp into this block, use it.
568 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
571 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
573 CmpInst::Create(CI->getOpcode(),
574 CI->getPredicate(), CI->getOperand(0),
575 CI->getOperand(1), "", InsertPt);
579 // Replace a use of the cmp with a use of the new cmp.
580 TheUse = InsertedCmp;
584 // If we removed all uses, nuke the cmp.
586 CI->eraseFromParent();
592 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
594 void replaceCall(Value *With) {
595 CI->replaceAllUsesWith(With);
596 CI->eraseFromParent();
598 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
599 if (ConstantInt *SizeCI =
600 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
601 return SizeCI->isAllOnesValue();
605 } // end anonymous namespace
607 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
608 BasicBlock *BB = CI->getParent();
610 // Lower inline assembly if we can.
611 // If we found an inline asm expession, and if the target knows how to
612 // lower it to normal LLVM code, do so now.
613 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
614 if (TLI->ExpandInlineAsm(CI)) {
615 // Avoid invalidating the iterator.
616 CurInstIterator = BB->begin();
617 // Avoid processing instructions out of order, which could cause
618 // reuse before a value is defined.
622 // Sink address computing for memory operands into the block.
623 if (OptimizeInlineAsmInst(CI))
627 // Lower all uses of llvm.objectsize.*
628 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
629 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
630 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
631 Type *ReturnTy = CI->getType();
632 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
634 // Substituting this can cause recursive simplifications, which can
635 // invalidate our iterator. Use a WeakVH to hold onto it in case this
637 WeakVH IterHandle(CurInstIterator);
639 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
640 TLInfo, ModifiedDT ? 0 : DT);
642 // If the iterator instruction was recursively deleted, start over at the
643 // start of the block.
644 if (IterHandle != CurInstIterator) {
645 CurInstIterator = BB->begin();
652 SmallVector<Value*, 2> PtrOps;
654 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
655 while (!PtrOps.empty())
656 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
660 // From here on out we're working with named functions.
661 if (CI->getCalledFunction() == 0) return false;
663 // We'll need DataLayout from here on out.
664 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
665 if (!TD) return false;
667 // Lower all default uses of _chk calls. This is very similar
668 // to what InstCombineCalls does, but here we are only lowering calls
669 // that have the default "don't know" as the objectsize. Anything else
670 // should be left alone.
671 CodeGenPrepareFortifiedLibCalls Simplifier;
672 return Simplifier.fold(CI, TD, TLInfo);
675 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
676 /// instructions to the predecessor to enable tail call optimizations. The
677 /// case it is currently looking for is:
680 /// %tmp0 = tail call i32 @f0()
683 /// %tmp1 = tail call i32 @f1()
686 /// %tmp2 = tail call i32 @f2()
689 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
697 /// %tmp0 = tail call i32 @f0()
700 /// %tmp1 = tail call i32 @f1()
703 /// %tmp2 = tail call i32 @f2()
706 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
710 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
715 BitCastInst *BCI = 0;
716 Value *V = RI->getReturnValue();
718 BCI = dyn_cast<BitCastInst>(V);
720 V = BCI->getOperand(0);
722 PN = dyn_cast<PHINode>(V);
727 if (PN && PN->getParent() != BB)
730 // It's not safe to eliminate the sign / zero extension of the return value.
731 // See llvm::isInTailCallPosition().
732 const Function *F = BB->getParent();
733 Attribute CallerRetAttr = F->getAttributes().getRetAttributes();
734 if (CallerRetAttr.hasAttribute(Attribute::ZExt) ||
735 CallerRetAttr.hasAttribute(Attribute::SExt))
738 // Make sure there are no instructions between the PHI and return, or that the
739 // return is the first instruction in the block.
741 BasicBlock::iterator BI = BB->begin();
742 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
744 // Also skip over the bitcast.
749 BasicBlock::iterator BI = BB->begin();
750 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
755 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
757 SmallVector<CallInst*, 4> TailCalls;
759 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
760 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
761 // Make sure the phi value is indeed produced by the tail call.
762 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
763 TLI->mayBeEmittedAsTailCall(CI))
764 TailCalls.push_back(CI);
767 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
768 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
769 if (!VisitedBBs.insert(*PI))
772 BasicBlock::InstListType &InstList = (*PI)->getInstList();
773 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
774 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
775 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
779 CallInst *CI = dyn_cast<CallInst>(&*RI);
780 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
781 TailCalls.push_back(CI);
785 bool Changed = false;
786 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
787 CallInst *CI = TailCalls[i];
790 // Conservatively require the attributes of the call to match those of the
791 // return. Ignore noalias because it doesn't affect the call sequence.
792 Attribute CalleeRetAttr = CS.getAttributes().getRetAttributes();
793 if (AttrBuilder(CalleeRetAttr).
794 removeAttribute(Attribute::NoAlias) !=
795 AttrBuilder(CallerRetAttr).
796 removeAttribute(Attribute::NoAlias))
799 // Make sure the call instruction is followed by an unconditional branch to
801 BasicBlock *CallBB = CI->getParent();
802 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
803 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
806 // Duplicate the return into CallBB.
807 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
808 ModifiedDT = Changed = true;
812 // If we eliminated all predecessors of the block, delete the block now.
813 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
814 BB->eraseFromParent();
819 //===----------------------------------------------------------------------===//
820 // Memory Optimization
821 //===----------------------------------------------------------------------===//
823 /// IsNonLocalValue - Return true if the specified values are defined in a
824 /// different basic block than BB.
825 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
826 if (Instruction *I = dyn_cast<Instruction>(V))
827 return I->getParent() != BB;
831 /// OptimizeMemoryInst - Load and Store Instructions often have
832 /// addressing modes that can do significant amounts of computation. As such,
833 /// instruction selection will try to get the load or store to do as much
834 /// computation as possible for the program. The problem is that isel can only
835 /// see within a single block. As such, we sink as much legal addressing mode
836 /// stuff into the block as possible.
838 /// This method is used to optimize both load/store and inline asms with memory
840 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
844 // Try to collapse single-value PHI nodes. This is necessary to undo
845 // unprofitable PRE transformations.
846 SmallVector<Value*, 8> worklist;
847 SmallPtrSet<Value*, 16> Visited;
848 worklist.push_back(Addr);
850 // Use a worklist to iteratively look through PHI nodes, and ensure that
851 // the addressing mode obtained from the non-PHI roots of the graph
853 Value *Consensus = 0;
854 unsigned NumUsesConsensus = 0;
855 bool IsNumUsesConsensusValid = false;
856 SmallVector<Instruction*, 16> AddrModeInsts;
857 ExtAddrMode AddrMode;
858 while (!worklist.empty()) {
859 Value *V = worklist.back();
862 // Break use-def graph loops.
863 if (!Visited.insert(V)) {
868 // For a PHI node, push all of its incoming values.
869 if (PHINode *P = dyn_cast<PHINode>(V)) {
870 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
871 worklist.push_back(P->getIncomingValue(i));
875 // For non-PHIs, determine the addressing mode being computed.
876 SmallVector<Instruction*, 16> NewAddrModeInsts;
877 ExtAddrMode NewAddrMode =
878 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
879 NewAddrModeInsts, *TLI);
881 // This check is broken into two cases with very similar code to avoid using
882 // getNumUses() as much as possible. Some values have a lot of uses, so
883 // calling getNumUses() unconditionally caused a significant compile-time
887 AddrMode = NewAddrMode;
888 AddrModeInsts = NewAddrModeInsts;
890 } else if (NewAddrMode == AddrMode) {
891 if (!IsNumUsesConsensusValid) {
892 NumUsesConsensus = Consensus->getNumUses();
893 IsNumUsesConsensusValid = true;
896 // Ensure that the obtained addressing mode is equivalent to that obtained
897 // for all other roots of the PHI traversal. Also, when choosing one
898 // such root as representative, select the one with the most uses in order
899 // to keep the cost modeling heuristics in AddressingModeMatcher
901 unsigned NumUses = V->getNumUses();
902 if (NumUses > NumUsesConsensus) {
904 NumUsesConsensus = NumUses;
905 AddrModeInsts = NewAddrModeInsts;
914 // If the addressing mode couldn't be determined, or if multiple different
915 // ones were determined, bail out now.
916 if (!Consensus) return false;
918 // Check to see if any of the instructions supersumed by this addr mode are
919 // non-local to I's BB.
920 bool AnyNonLocal = false;
921 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
922 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
928 // If all the instructions matched are already in this BB, don't do anything.
930 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
934 // Insert this computation right after this user. Since our caller is
935 // scanning from the top of the BB to the bottom, reuse of the expr are
936 // guaranteed to happen later.
937 IRBuilder<> Builder(MemoryInst);
939 // Now that we determined the addressing expression we want to use and know
940 // that we have to sink it into this block. Check to see if we have already
941 // done this for some other load/store instr in this block. If so, reuse the
943 Value *&SunkAddr = SunkAddrs[Addr];
945 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
947 if (SunkAddr->getType() != Addr->getType())
948 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
950 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
953 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
957 // Start with the base register. Do this first so that subsequent address
958 // matching finds it last, which will prevent it from trying to match it
959 // as the scaled value in case it happens to be a mul. That would be
960 // problematic if we've sunk a different mul for the scale, because then
961 // we'd end up sinking both muls.
962 if (AddrMode.BaseReg) {
963 Value *V = AddrMode.BaseReg;
964 if (V->getType()->isPointerTy())
965 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
966 if (V->getType() != IntPtrTy)
967 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
971 // Add the scale value.
972 if (AddrMode.Scale) {
973 Value *V = AddrMode.ScaledReg;
974 if (V->getType() == IntPtrTy) {
976 } else if (V->getType()->isPointerTy()) {
977 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
978 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
979 cast<IntegerType>(V->getType())->getBitWidth()) {
980 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
982 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
984 if (AddrMode.Scale != 1)
985 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
988 Result = Builder.CreateAdd(Result, V, "sunkaddr");
993 // Add in the BaseGV if present.
994 if (AddrMode.BaseGV) {
995 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
997 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1002 // Add in the Base Offset if present.
1003 if (AddrMode.BaseOffs) {
1004 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1006 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1012 SunkAddr = Constant::getNullValue(Addr->getType());
1014 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
1017 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
1019 // If we have no uses, recursively delete the value and all dead instructions
1021 if (Repl->use_empty()) {
1022 // This can cause recursive deletion, which can invalidate our iterator.
1023 // Use a WeakVH to hold onto it in case this happens.
1024 WeakVH IterHandle(CurInstIterator);
1025 BasicBlock *BB = CurInstIterator->getParent();
1027 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
1029 if (IterHandle != CurInstIterator) {
1030 // If the iterator instruction was recursively deleted, start over at the
1031 // start of the block.
1032 CurInstIterator = BB->begin();
1035 // This address is now available for reassignment, so erase the table
1036 // entry; we don't want to match some completely different instruction.
1037 SunkAddrs[Addr] = 0;
1044 /// OptimizeInlineAsmInst - If there are any memory operands, use
1045 /// OptimizeMemoryInst to sink their address computing into the block when
1046 /// possible / profitable.
1047 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1048 bool MadeChange = false;
1050 TargetLowering::AsmOperandInfoVector
1051 TargetConstraints = TLI->ParseConstraints(CS);
1053 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1054 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1056 // Compute the constraint code and ConstraintType to use.
1057 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1059 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1060 OpInfo.isIndirect) {
1061 Value *OpVal = CS->getArgOperand(ArgNo++);
1062 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1063 } else if (OpInfo.Type == InlineAsm::isInput)
1070 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1071 /// basic block as the load, unless conditions are unfavorable. This allows
1072 /// SelectionDAG to fold the extend into the load.
1074 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1075 // Look for a load being extended.
1076 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1077 if (!LI) return false;
1079 // If they're already in the same block, there's nothing to do.
1080 if (LI->getParent() == I->getParent())
1083 // If the load has other users and the truncate is not free, this probably
1084 // isn't worthwhile.
1085 if (!LI->hasOneUse() &&
1086 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1087 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1088 !TLI->isTruncateFree(I->getType(), LI->getType()))
1091 // Check whether the target supports casts folded into loads.
1093 if (isa<ZExtInst>(I))
1094 LType = ISD::ZEXTLOAD;
1096 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1097 LType = ISD::SEXTLOAD;
1099 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1102 // Move the extend into the same block as the load, so that SelectionDAG
1104 I->removeFromParent();
1110 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1111 BasicBlock *DefBB = I->getParent();
1113 // If the result of a {s|z}ext and its source are both live out, rewrite all
1114 // other uses of the source with result of extension.
1115 Value *Src = I->getOperand(0);
1116 if (Src->hasOneUse())
1119 // Only do this xform if truncating is free.
1120 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1123 // Only safe to perform the optimization if the source is also defined in
1125 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1128 bool DefIsLiveOut = false;
1129 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1131 Instruction *User = cast<Instruction>(*UI);
1133 // Figure out which BB this ext is used in.
1134 BasicBlock *UserBB = User->getParent();
1135 if (UserBB == DefBB) continue;
1136 DefIsLiveOut = true;
1142 // Make sure non of the uses are PHI nodes.
1143 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1145 Instruction *User = cast<Instruction>(*UI);
1146 BasicBlock *UserBB = User->getParent();
1147 if (UserBB == DefBB) continue;
1148 // Be conservative. We don't want this xform to end up introducing
1149 // reloads just before load / store instructions.
1150 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1154 // InsertedTruncs - Only insert one trunc in each block once.
1155 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1157 bool MadeChange = false;
1158 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1160 Use &TheUse = UI.getUse();
1161 Instruction *User = cast<Instruction>(*UI);
1163 // Figure out which BB this ext is used in.
1164 BasicBlock *UserBB = User->getParent();
1165 if (UserBB == DefBB) continue;
1167 // Both src and def are live in this block. Rewrite the use.
1168 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1170 if (!InsertedTrunc) {
1171 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1172 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1175 // Replace a use of the {s|z}ext source with a use of the result.
1176 TheUse = InsertedTrunc;
1184 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1185 /// turned into an explicit branch.
1186 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1187 // FIXME: This should use the same heuristics as IfConversion to determine
1188 // whether a select is better represented as a branch. This requires that
1189 // branch probability metadata is preserved for the select, which is not the
1192 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1194 // If the branch is predicted right, an out of order CPU can avoid blocking on
1195 // the compare. Emit cmovs on compares with a memory operand as branches to
1196 // avoid stalls on the load from memory. If the compare has more than one use
1197 // there's probably another cmov or setcc around so it's not worth emitting a
1202 Value *CmpOp0 = Cmp->getOperand(0);
1203 Value *CmpOp1 = Cmp->getOperand(1);
1205 // We check that the memory operand has one use to avoid uses of the loaded
1206 // value directly after the compare, making branches unprofitable.
1207 return Cmp->hasOneUse() &&
1208 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1209 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1213 /// If we have a SelectInst that will likely profit from branch prediction,
1214 /// turn it into a branch.
1215 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1216 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1218 // Can we convert the 'select' to CF ?
1219 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
1222 TargetLowering::SelectSupportKind SelectKind;
1224 SelectKind = TargetLowering::VectorMaskSelect;
1225 else if (SI->getType()->isVectorTy())
1226 SelectKind = TargetLowering::ScalarCondVectorVal;
1228 SelectKind = TargetLowering::ScalarValSelect;
1230 // Do we have efficient codegen support for this kind of 'selects' ?
1231 if (TLI->isSelectSupported(SelectKind)) {
1232 // We have efficient codegen support for the select instruction.
1233 // Check if it is profitable to keep this 'select'.
1234 if (!TLI->isPredictableSelectExpensive() ||
1235 !isFormingBranchFromSelectProfitable(SI))
1241 // First, we split the block containing the select into 2 blocks.
1242 BasicBlock *StartBlock = SI->getParent();
1243 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1244 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1246 // Create a new block serving as the landing pad for the branch.
1247 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1248 NextBlock->getParent(), NextBlock);
1250 // Move the unconditional branch from the block with the select in it into our
1251 // landing pad block.
1252 StartBlock->getTerminator()->eraseFromParent();
1253 BranchInst::Create(NextBlock, SmallBlock);
1255 // Insert the real conditional branch based on the original condition.
1256 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1258 // The select itself is replaced with a PHI Node.
1259 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1261 PN->addIncoming(SI->getTrueValue(), StartBlock);
1262 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1263 SI->replaceAllUsesWith(PN);
1264 SI->eraseFromParent();
1266 // Instruct OptimizeBlock to skip to the next block.
1267 CurInstIterator = StartBlock->end();
1268 ++NumSelectsExpanded;
1272 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1273 if (PHINode *P = dyn_cast<PHINode>(I)) {
1274 // It is possible for very late stage optimizations (such as SimplifyCFG)
1275 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1276 // trivial PHI, go ahead and zap it here.
1277 if (Value *V = SimplifyInstruction(P)) {
1278 P->replaceAllUsesWith(V);
1279 P->eraseFromParent();
1286 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1287 // If the source of the cast is a constant, then this should have
1288 // already been constant folded. The only reason NOT to constant fold
1289 // it is if something (e.g. LSR) was careful to place the constant
1290 // evaluation in a block other than then one that uses it (e.g. to hoist
1291 // the address of globals out of a loop). If this is the case, we don't
1292 // want to forward-subst the cast.
1293 if (isa<Constant>(CI->getOperand(0)))
1296 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1299 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1300 bool MadeChange = MoveExtToFormExtLoad(I);
1301 return MadeChange | OptimizeExtUses(I);
1306 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1307 return OptimizeCmpExpression(CI);
1309 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1311 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1315 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1317 return OptimizeMemoryInst(I, SI->getOperand(1),
1318 SI->getOperand(0)->getType());
1322 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1323 if (GEPI->hasAllZeroIndices()) {
1324 /// The GEP operand must be a pointer, so must its result -> BitCast
1325 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1326 GEPI->getName(), GEPI);
1327 GEPI->replaceAllUsesWith(NC);
1328 GEPI->eraseFromParent();
1336 if (CallInst *CI = dyn_cast<CallInst>(I))
1337 return OptimizeCallInst(CI);
1339 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1340 return OptimizeSelectInst(SI);
1345 // In this pass we look for GEP and cast instructions that are used
1346 // across basic blocks and rewrite them to improve basic-block-at-a-time
1348 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1350 bool MadeChange = false;
1352 CurInstIterator = BB.begin();
1353 while (CurInstIterator != BB.end())
1354 MadeChange |= OptimizeInst(CurInstIterator++);
1356 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1361 // llvm.dbg.value is far away from the value then iSel may not be able
1362 // handle it properly. iSel will drop llvm.dbg.value if it can not
1363 // find a node corresponding to the value.
1364 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1365 bool MadeChange = false;
1366 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1367 Instruction *PrevNonDbgInst = NULL;
1368 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1369 Instruction *Insn = BI; ++BI;
1370 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1372 PrevNonDbgInst = Insn;
1376 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1377 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1378 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1379 DVI->removeFromParent();
1380 if (isa<PHINode>(VI))
1381 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1383 DVI->insertAfter(VI);