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 DenseMap<Value*,Value*> &SunkAddrs);
113 bool OptimizeInlineAsmInst(CallInst *CS);
114 bool OptimizeCallInst(CallInst *CI);
115 bool MoveExtToFormExtLoad(Instruction *I);
116 bool OptimizeExtUses(Instruction *I);
117 void findLoopBackEdges(const Function &F);
121 char CodeGenPrepare::ID = 0;
122 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
123 "Optimize for code generation", false, false)
125 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
126 return new CodeGenPrepare(TLI);
129 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
131 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
132 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
133 FindFunctionBackedges(F, Edges);
135 BackEdges.insert(Edges.begin(), Edges.end());
139 bool CodeGenPrepare::runOnFunction(Function &F) {
140 bool EverMadeChange = false;
142 DT = getAnalysisIfAvailable<DominatorTree>();
143 PFI = getAnalysisIfAvailable<ProfileInfo>();
144 // First pass, eliminate blocks that contain only PHI nodes and an
145 // unconditional branch.
146 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
148 // Now find loop back edges, but only if they are being used to decide which
149 // critical edges to split.
150 if (CriticalEdgeSplit)
151 findLoopBackEdges(F);
153 bool MadeChange = true;
156 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
157 MadeChange |= OptimizeBlock(*BB);
158 EverMadeChange |= MadeChange;
163 return EverMadeChange;
166 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
167 /// debug info directives, and an unconditional branch. Passes before isel
168 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
169 /// isel. Start by eliminating these blocks so we can split them the way we
171 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
172 bool MadeChange = false;
173 // Note that this intentionally skips the entry block.
174 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
175 BasicBlock *BB = I++;
177 // If this block doesn't end with an uncond branch, ignore it.
178 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
179 if (!BI || !BI->isUnconditional())
182 // If the instruction before the branch (skipping debug info) isn't a phi
183 // node, then other stuff is happening here.
184 BasicBlock::iterator BBI = BI;
185 if (BBI != BB->begin()) {
187 while (isa<DbgInfoIntrinsic>(BBI)) {
188 if (BBI == BB->begin())
192 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
196 // Do not break infinite loops.
197 BasicBlock *DestBB = BI->getSuccessor(0);
201 if (!CanMergeBlocks(BB, DestBB))
204 EliminateMostlyEmptyBlock(BB);
210 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
211 /// single uncond branch between them, and BB contains no other non-phi
213 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
214 const BasicBlock *DestBB) const {
215 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
216 // the successor. If there are more complex condition (e.g. preheaders),
217 // don't mess around with them.
218 BasicBlock::const_iterator BBI = BB->begin();
219 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
220 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
222 const Instruction *User = cast<Instruction>(*UI);
223 if (User->getParent() != DestBB || !isa<PHINode>(User))
225 // If User is inside DestBB block and it is a PHINode then check
226 // incoming value. If incoming value is not from BB then this is
227 // a complex condition (e.g. preheaders) we want to avoid here.
228 if (User->getParent() == DestBB) {
229 if (const PHINode *UPN = dyn_cast<PHINode>(User))
230 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
231 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
232 if (Insn && Insn->getParent() == BB &&
233 Insn->getParent() != UPN->getIncomingBlock(I))
240 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
241 // and DestBB may have conflicting incoming values for the block. If so, we
242 // can't merge the block.
243 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
244 if (!DestBBPN) return true; // no conflict.
246 // Collect the preds of BB.
247 SmallPtrSet<const BasicBlock*, 16> BBPreds;
248 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
249 // It is faster to get preds from a PHI than with pred_iterator.
250 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
251 BBPreds.insert(BBPN->getIncomingBlock(i));
253 BBPreds.insert(pred_begin(BB), pred_end(BB));
256 // Walk the preds of DestBB.
257 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
258 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
259 if (BBPreds.count(Pred)) { // Common predecessor?
260 BBI = DestBB->begin();
261 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
262 const Value *V1 = PN->getIncomingValueForBlock(Pred);
263 const Value *V2 = PN->getIncomingValueForBlock(BB);
265 // If V2 is a phi node in BB, look up what the mapped value will be.
266 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
267 if (V2PN->getParent() == BB)
268 V2 = V2PN->getIncomingValueForBlock(Pred);
270 // If there is a conflict, bail out.
271 if (V1 != V2) return false;
280 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
281 /// an unconditional branch in it.
282 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
283 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
284 BasicBlock *DestBB = BI->getSuccessor(0);
286 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
288 // If the destination block has a single pred, then this is a trivial edge,
290 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
291 if (SinglePred != DestBB) {
292 // Remember if SinglePred was the entry block of the function. If so, we
293 // will need to move BB back to the entry position.
294 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
295 MergeBasicBlockIntoOnlyPred(DestBB, this);
297 if (isEntry && BB != &BB->getParent()->getEntryBlock())
298 BB->moveBefore(&BB->getParent()->getEntryBlock());
300 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
305 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
306 // to handle the new incoming edges it is about to have.
308 for (BasicBlock::iterator BBI = DestBB->begin();
309 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
310 // Remove the incoming value for BB, and remember it.
311 Value *InVal = PN->removeIncomingValue(BB, false);
313 // Two options: either the InVal is a phi node defined in BB or it is some
314 // value that dominates BB.
315 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
316 if (InValPhi && InValPhi->getParent() == BB) {
317 // Add all of the input values of the input PHI as inputs of this phi.
318 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
319 PN->addIncoming(InValPhi->getIncomingValue(i),
320 InValPhi->getIncomingBlock(i));
322 // Otherwise, add one instance of the dominating value for each edge that
323 // we will be adding.
324 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
325 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
326 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
328 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
329 PN->addIncoming(InVal, *PI);
334 // The PHIs are now updated, change everything that refers to BB to use
335 // DestBB and remove BB.
336 BB->replaceAllUsesWith(DestBB);
338 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
339 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
340 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
341 DT->changeImmediateDominator(DestBB, NewIDom);
345 PFI->replaceAllUses(BB, DestBB);
346 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
348 BB->eraseFromParent();
351 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
354 /// FindReusablePredBB - Check all of the predecessors of the block DestPHI
355 /// lives in to see if there is a block that we can reuse as a critical edge
357 static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
358 BasicBlock *Dest = DestPHI->getParent();
360 /// TIPHIValues - This array is lazily computed to determine the values of
361 /// PHIs in Dest that TI would provide.
362 SmallVector<Value*, 32> TIPHIValues;
364 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
365 unsigned TIBBEntryNo = 0;
367 // Check to see if Dest has any blocks that can be used as a split edge for
369 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
370 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
371 // To be usable, the pred has to end with an uncond branch to the dest.
372 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
373 if (!PredBr || !PredBr->isUnconditional())
375 // Must be empty other than the branch and debug info.
376 BasicBlock::iterator I = Pred->begin();
377 while (isa<DbgInfoIntrinsic>(I))
381 // Cannot be the entry block; its label does not get emitted.
382 if (Pred == &Dest->getParent()->getEntryBlock())
385 // Finally, since we know that Dest has phi nodes in it, we have to make
386 // sure that jumping to Pred will have the same effect as going to Dest in
387 // terms of PHI values.
390 unsigned PredEntryNo = pi;
392 bool FoundMatch = true;
393 for (BasicBlock::iterator I = Dest->begin();
394 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
395 if (PHINo == TIPHIValues.size()) {
396 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
397 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
398 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
401 // If the PHI entry doesn't work, we can't use this pred.
402 if (PN->getIncomingBlock(PredEntryNo) != Pred)
403 PredEntryNo = PN->getBasicBlockIndex(Pred);
405 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
411 // If we found a workable predecessor, change TI to branch to Succ.
419 /// SplitEdgeNicely - Split the critical edge from TI to its specified
420 /// successor if it will improve codegen. We only do this if the successor has
421 /// phi nodes (otherwise critical edges are ok). If there is already another
422 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
423 /// instead of introducing a new block.
424 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
425 SmallSet<std::pair<const BasicBlock*,
426 const BasicBlock*>, 8> &BackEdges,
428 BasicBlock *TIBB = TI->getParent();
429 BasicBlock *Dest = TI->getSuccessor(SuccNum);
430 assert(isa<PHINode>(Dest->begin()) &&
431 "This should only be called if Dest has a PHI!");
432 PHINode *DestPHI = cast<PHINode>(Dest->begin());
434 // Do not split edges to EH landing pads.
435 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
436 if (Invoke->getSuccessor(1) == Dest)
439 // As a hack, never split backedges of loops. Even though the copy for any
440 // PHIs inserted on the backedge would be dead for exits from the loop, we
441 // assume that the cost of *splitting* the backedge would be too high.
442 if (BackEdges.count(std::make_pair(TIBB, Dest)))
445 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
446 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
448 PFI->splitEdge(TIBB, Dest, ReuseBB);
449 Dest->removePredecessor(TIBB);
450 TI->setSuccessor(SuccNum, ReuseBB);
454 SplitCriticalEdge(TI, SuccNum, P, true);
458 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
459 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
460 /// sink it into user blocks to reduce the number of virtual
461 /// registers that must be created and coalesced.
463 /// Return true if any changes are made.
465 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
466 // If this is a noop copy,
467 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
468 EVT DstVT = TLI.getValueType(CI->getType());
470 // This is an fp<->int conversion?
471 if (SrcVT.isInteger() != DstVT.isInteger())
474 // If this is an extension, it will be a zero or sign extension, which
476 if (SrcVT.bitsLT(DstVT)) return false;
478 // If these values will be promoted, find out what they will be promoted
479 // to. This helps us consider truncates on PPC as noop copies when they
481 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
482 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
483 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
484 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
486 // If, after promotion, these are the same types, this is a noop copy.
490 BasicBlock *DefBB = CI->getParent();
492 /// InsertedCasts - Only insert a cast in each block once.
493 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
495 bool MadeChange = false;
496 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
498 Use &TheUse = UI.getUse();
499 Instruction *User = cast<Instruction>(*UI);
501 // Figure out which BB this cast is used in. For PHI's this is the
502 // appropriate predecessor block.
503 BasicBlock *UserBB = User->getParent();
504 if (PHINode *PN = dyn_cast<PHINode>(User)) {
505 UserBB = PN->getIncomingBlock(UI);
508 // Preincrement use iterator so we don't invalidate it.
511 // If this user is in the same block as the cast, don't change the cast.
512 if (UserBB == DefBB) continue;
514 // If we have already inserted a cast into this block, use it.
515 CastInst *&InsertedCast = InsertedCasts[UserBB];
518 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
521 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
526 // Replace a use of the cast with a use of the new cast.
527 TheUse = InsertedCast;
531 // If we removed all uses, nuke the cast.
532 if (CI->use_empty()) {
533 CI->eraseFromParent();
540 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
541 /// the number of virtual registers that must be created and coalesced. This is
542 /// a clear win except on targets with multiple condition code registers
543 /// (PowerPC), where it might lose; some adjustment may be wanted there.
545 /// Return true if any changes are made.
546 static bool OptimizeCmpExpression(CmpInst *CI) {
547 BasicBlock *DefBB = CI->getParent();
549 /// InsertedCmp - Only insert a cmp in each block once.
550 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
552 bool MadeChange = false;
553 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
555 Use &TheUse = UI.getUse();
556 Instruction *User = cast<Instruction>(*UI);
558 // Preincrement use iterator so we don't invalidate it.
561 // Don't bother for PHI nodes.
562 if (isa<PHINode>(User))
565 // Figure out which BB this cmp is used in.
566 BasicBlock *UserBB = User->getParent();
568 // If this user is in the same block as the cmp, don't change the cmp.
569 if (UserBB == DefBB) continue;
571 // If we have already inserted a cmp into this block, use it.
572 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
575 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
578 CmpInst::Create(CI->getOpcode(),
579 CI->getPredicate(), CI->getOperand(0),
580 CI->getOperand(1), "", InsertPt);
584 // Replace a use of the cmp with a use of the new cmp.
585 TheUse = InsertedCmp;
589 // If we removed all uses, nuke the cmp.
591 CI->eraseFromParent();
597 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
599 void replaceCall(Value *With) {
600 CI->replaceAllUsesWith(With);
601 CI->eraseFromParent();
603 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
604 if (ConstantInt *SizeCI =
605 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
606 return SizeCI->isAllOnesValue();
610 } // end anonymous namespace
612 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
613 BasicBlock *BB = CI->getParent();
615 // Lower inline assembly if we can.
616 // If we found an inline asm expession, and if the target knows how to
617 // lower it to normal LLVM code, do so now.
618 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
619 if (TLI->ExpandInlineAsm(CI)) {
620 // Avoid invalidating the iterator.
621 CurInstIterator = BB->begin();
622 // Avoid processing instructions out of order, which could cause
623 // reuse before a value is defined.
627 // Sink address computing for memory operands into the block.
628 if (OptimizeInlineAsmInst(CI))
632 // Lower all uses of llvm.objectsize.*
633 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
634 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
635 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
636 const Type *ReturnTy = CI->getType();
637 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
639 // Substituting this can cause recursive simplifications, which can
640 // invalidate our iterator. Use a WeakVH to hold onto it in case this
642 WeakVH IterHandle(CurInstIterator);
644 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0, DT);
646 // If the iterator instruction was recursively deleted, start over at the
647 // start of the block.
648 if (IterHandle != CurInstIterator)
649 CurInstIterator = BB->begin();
653 // From here on out we're working with named functions.
654 if (CI->getCalledFunction() == 0) return false;
656 // We'll need TargetData from here on out.
657 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
658 if (!TD) return false;
660 // Lower all default uses of _chk calls. This is very similar
661 // to what InstCombineCalls does, but here we are only lowering calls
662 // that have the default "don't know" as the objectsize. Anything else
663 // should be left alone.
664 CodeGenPrepareFortifiedLibCalls Simplifier;
665 return Simplifier.fold(CI, TD);
668 //===----------------------------------------------------------------------===//
669 // Memory Optimization
670 //===----------------------------------------------------------------------===//
672 /// IsNonLocalValue - Return true if the specified values are defined in a
673 /// different basic block than BB.
674 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
675 if (Instruction *I = dyn_cast<Instruction>(V))
676 return I->getParent() != BB;
680 /// OptimizeMemoryInst - Load and Store Instructions often have
681 /// addressing modes that can do significant amounts of computation. As such,
682 /// instruction selection will try to get the load or store to do as much
683 /// computation as possible for the program. The problem is that isel can only
684 /// see within a single block. As such, we sink as much legal addressing mode
685 /// stuff into the block as possible.
687 /// This method is used to optimize both load/store and inline asms with memory
689 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
690 const Type *AccessTy,
691 DenseMap<Value*,Value*> &SunkAddrs) {
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 NumUses = 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 if (V->getNumUses() > NumUses) {
739 NumUses = V->getNumUses();
740 AddrMode = NewAddrMode;
741 AddrModeInsts = NewAddrModeInsts;
750 // If the addressing mode couldn't be determined, or if multiple different
751 // ones were determined, bail out now.
752 if (!Consensus) return false;
754 // Check to see if any of the instructions supersumed by this addr mode are
755 // non-local to I's BB.
756 bool AnyNonLocal = false;
757 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
758 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
764 // If all the instructions matched are already in this BB, don't do anything.
766 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
770 // Insert this computation right after this user. Since our caller is
771 // scanning from the top of the BB to the bottom, reuse of the expr are
772 // guaranteed to happen later.
773 BasicBlock::iterator InsertPt = MemoryInst;
775 // Now that we determined the addressing expression we want to use and know
776 // that we have to sink it into this block. Check to see if we have already
777 // done this for some other load/store instr in this block. If so, reuse the
779 Value *&SunkAddr = SunkAddrs[Addr];
781 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
783 if (SunkAddr->getType() != Addr->getType())
784 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
786 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
788 const Type *IntPtrTy =
789 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
793 // Start with the base register. Do this first so that subsequent address
794 // matching finds it last, which will prevent it from trying to match it
795 // as the scaled value in case it happens to be a mul. That would be
796 // problematic if we've sunk a different mul for the scale, because then
797 // we'd end up sinking both muls.
798 if (AddrMode.BaseReg) {
799 Value *V = AddrMode.BaseReg;
800 if (V->getType()->isPointerTy())
801 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
802 if (V->getType() != IntPtrTy)
803 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
804 "sunkaddr", InsertPt);
808 // Add the scale value.
809 if (AddrMode.Scale) {
810 Value *V = AddrMode.ScaledReg;
811 if (V->getType() == IntPtrTy) {
813 } else if (V->getType()->isPointerTy()) {
814 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
815 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
816 cast<IntegerType>(V->getType())->getBitWidth()) {
817 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
819 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
821 if (AddrMode.Scale != 1)
822 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
824 "sunkaddr", InsertPt);
826 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
831 // Add in the BaseGV if present.
832 if (AddrMode.BaseGV) {
833 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
836 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
841 // Add in the Base Offset if present.
842 if (AddrMode.BaseOffs) {
843 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
845 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
851 SunkAddr = Constant::getNullValue(Addr->getType());
853 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
856 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
858 if (Repl->use_empty()) {
859 RecursivelyDeleteTriviallyDeadInstructions(Repl);
860 // This address is now available for reassignment, so erase the table entry;
861 // we don't want to match some completely different instruction.
868 /// OptimizeInlineAsmInst - If there are any memory operands, use
869 /// OptimizeMemoryInst to sink their address computing into the block when
870 /// possible / profitable.
871 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
872 bool MadeChange = false;
874 TargetLowering::AsmOperandInfoVector
875 TargetConstraints = TLI->ParseConstraints(CS);
877 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
878 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
880 // Compute the constraint code and ConstraintType to use.
881 TLI->ComputeConstraintToUse(OpInfo, SDValue());
883 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
885 Value *OpVal = CS->getArgOperand(ArgNo++);
886 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), SunkAddrs);
887 } else if (OpInfo.Type == InlineAsm::isInput)
894 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
895 /// basic block as the load, unless conditions are unfavorable. This allows
896 /// SelectionDAG to fold the extend into the load.
898 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
899 // Look for a load being extended.
900 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
901 if (!LI) return false;
903 // If they're already in the same block, there's nothing to do.
904 if (LI->getParent() == I->getParent())
907 // If the load has other users and the truncate is not free, this probably
909 if (!LI->hasOneUse() &&
910 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
911 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
912 !TLI->isTruncateFree(I->getType(), LI->getType()))
915 // Check whether the target supports casts folded into loads.
917 if (isa<ZExtInst>(I))
918 LType = ISD::ZEXTLOAD;
920 assert(isa<SExtInst>(I) && "Unexpected ext type!");
921 LType = ISD::SEXTLOAD;
923 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
926 // Move the extend into the same block as the load, so that SelectionDAG
928 I->removeFromParent();
934 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
935 BasicBlock *DefBB = I->getParent();
937 // If the result of a {s|z}ext and its source are both live out, rewrite all
938 // other uses of the source with result of extension.
939 Value *Src = I->getOperand(0);
940 if (Src->hasOneUse())
943 // Only do this xform if truncating is free.
944 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
947 // Only safe to perform the optimization if the source is also defined in
949 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
952 bool DefIsLiveOut = false;
953 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
955 Instruction *User = cast<Instruction>(*UI);
957 // Figure out which BB this ext is used in.
958 BasicBlock *UserBB = User->getParent();
959 if (UserBB == DefBB) continue;
966 // Make sure non of the uses are PHI nodes.
967 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
969 Instruction *User = cast<Instruction>(*UI);
970 BasicBlock *UserBB = User->getParent();
971 if (UserBB == DefBB) continue;
972 // Be conservative. We don't want this xform to end up introducing
973 // reloads just before load / store instructions.
974 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
978 // InsertedTruncs - Only insert one trunc in each block once.
979 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
981 bool MadeChange = false;
982 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
984 Use &TheUse = UI.getUse();
985 Instruction *User = cast<Instruction>(*UI);
987 // Figure out which BB this ext is used in.
988 BasicBlock *UserBB = User->getParent();
989 if (UserBB == DefBB) continue;
991 // Both src and def are live in this block. Rewrite the use.
992 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
994 if (!InsertedTrunc) {
995 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
997 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1000 // Replace a use of the {s|z}ext source with a use of the result.
1001 TheUse = InsertedTrunc;
1009 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1010 bool MadeChange = false;
1012 if (PHINode *P = dyn_cast<PHINode>(I)) {
1013 // It is possible for very late stage optimizations (such as SimplifyCFG)
1014 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1015 // trivial PHI, go ahead and zap it here.
1016 if (Value *V = SimplifyInstruction(P)) {
1017 P->replaceAllUsesWith(V);
1018 P->eraseFromParent();
1021 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1022 // If the source of the cast is a constant, then this should have
1023 // already been constant folded. The only reason NOT to constant fold
1024 // it is if something (e.g. LSR) was careful to place the constant
1025 // evaluation in a block other than then one that uses it (e.g. to hoist
1026 // the address of globals out of a loop). If this is the case, we don't
1027 // want to forward-subst the cast.
1028 if (isa<Constant>(CI->getOperand(0)))
1031 bool Change = false;
1033 Change = OptimizeNoopCopyExpression(CI, *TLI);
1034 MadeChange |= Change;
1037 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
1038 MadeChange |= MoveExtToFormExtLoad(I);
1039 MadeChange |= OptimizeExtUses(I);
1041 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1042 MadeChange |= OptimizeCmpExpression(CI);
1043 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1045 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1047 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1049 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1050 SI->getOperand(0)->getType(),
1052 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1053 if (GEPI->hasAllZeroIndices()) {
1054 /// The GEP operand must be a pointer, so must its result -> BitCast
1055 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1056 GEPI->getName(), GEPI);
1057 GEPI->replaceAllUsesWith(NC);
1058 GEPI->eraseFromParent();
1063 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1064 MadeChange |= OptimizeCallInst(CI);
1070 // In this pass we look for GEP and cast instructions that are used
1071 // across basic blocks and rewrite them to improve basic-block-at-a-time
1073 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1074 bool MadeChange = false;
1076 // Split all critical edges where the dest block has a PHI.
1077 if (CriticalEdgeSplit) {
1078 TerminatorInst *BBTI = BB.getTerminator();
1079 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
1080 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1081 BasicBlock *SuccBB = BBTI->getSuccessor(i);
1082 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1083 SplitEdgeNicely(BBTI, i, BackEdges, this);
1090 CurInstIterator = BB.begin();
1091 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1092 MadeChange |= OptimizeInst(CurInstIterator++);