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/CodeGen/Passes.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/ValueMap.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/Pass.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/TargetLibraryInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/BuildLibCalls.h"
44 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
45 #include "llvm/Transforms/Utils/Local.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");
60 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
61 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
62 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
64 static cl::opt<bool> DisableBranchOpts(
65 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
66 cl::desc("Disable branch optimizations in CodeGenPrepare"));
68 static cl::opt<bool> DisableSelectToBranch(
69 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
70 cl::desc("Disable select to branch conversion."));
73 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
74 typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
76 class CodeGenPrepare : public FunctionPass {
77 /// TLI - Keep a pointer of a TargetLowering to consult for determining
78 /// transformation profitability.
79 const TargetMachine *TM;
80 const TargetLowering *TLI;
81 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 ValueMap<Value*, Value*> SunkAddrs;
94 /// Keeps track of all truncates inserted for the current function.
95 SetOfInstrs InsertedTruncsSet;
96 /// Keeps track of the type of the related instruction before their
97 /// promotion for the current function.
98 InstrToOrigTy PromotedInsts;
100 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
104 /// OptSize - True if optimizing for size.
108 static char ID; // Pass identification, replacement for typeid
109 explicit CodeGenPrepare(const TargetMachine *TM = 0)
110 : FunctionPass(ID), TM(TM), TLI(0) {
111 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
113 bool runOnFunction(Function &F);
115 const char *getPassName() const { return "CodeGen Prepare"; }
117 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
118 AU.addPreserved<DominatorTreeWrapperPass>();
119 AU.addRequired<TargetLibraryInfo>();
123 bool EliminateFallThrough(Function &F);
124 bool EliminateMostlyEmptyBlocks(Function &F);
125 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
126 void EliminateMostlyEmptyBlock(BasicBlock *BB);
127 bool OptimizeBlock(BasicBlock &BB);
128 bool OptimizeInst(Instruction *I);
129 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
130 bool OptimizeInlineAsmInst(CallInst *CS);
131 bool OptimizeCallInst(CallInst *CI);
132 bool MoveExtToFormExtLoad(Instruction *I);
133 bool OptimizeExtUses(Instruction *I);
134 bool OptimizeSelectInst(SelectInst *SI);
135 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
136 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
137 bool PlaceDbgValues(Function &F);
141 char CodeGenPrepare::ID = 0;
142 static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
143 initializeTargetLibraryInfoPass(Registry);
144 PassInfo *PI = new PassInfo(
145 "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
146 PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
147 PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
148 Registry.registerPass(*PI, true);
152 void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
153 CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
156 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
157 return new CodeGenPrepare(TM);
160 bool CodeGenPrepare::runOnFunction(Function &F) {
161 bool EverMadeChange = false;
162 // Clear per function information.
163 InsertedTruncsSet.clear();
164 PromotedInsts.clear();
167 if (TM) TLI = TM->getTargetLowering();
168 TLInfo = &getAnalysis<TargetLibraryInfo>();
169 DominatorTreeWrapperPass *DTWP =
170 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
171 DT = DTWP ? &DTWP->getDomTree() : 0;
172 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
173 Attribute::OptimizeForSize);
175 /// This optimization identifies DIV instructions that can be
176 /// profitably bypassed and carried out with a shorter, faster divide.
177 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
178 const DenseMap<unsigned int, unsigned int> &BypassWidths =
179 TLI->getBypassSlowDivWidths();
180 for (Function::iterator I = F.begin(); I != F.end(); I++)
181 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
184 // Eliminate blocks that contain only PHI nodes and an
185 // unconditional branch.
186 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
188 // llvm.dbg.value is far away from the value then iSel may not be able
189 // handle it properly. iSel will drop llvm.dbg.value if it can not
190 // find a node corresponding to the value.
191 EverMadeChange |= PlaceDbgValues(F);
193 bool MadeChange = true;
196 for (Function::iterator I = F.begin(); I != F.end(); ) {
197 BasicBlock *BB = I++;
198 MadeChange |= OptimizeBlock(*BB);
200 EverMadeChange |= MadeChange;
205 if (!DisableBranchOpts) {
207 SmallPtrSet<BasicBlock*, 8> WorkList;
208 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
209 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
210 MadeChange |= ConstantFoldTerminator(BB, true);
211 if (!MadeChange) continue;
213 for (SmallVectorImpl<BasicBlock*>::iterator
214 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
215 if (pred_begin(*II) == pred_end(*II))
216 WorkList.insert(*II);
219 // Delete the dead blocks and any of their dead successors.
220 MadeChange |= !WorkList.empty();
221 while (!WorkList.empty()) {
222 BasicBlock *BB = *WorkList.begin();
224 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
228 for (SmallVectorImpl<BasicBlock*>::iterator
229 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
230 if (pred_begin(*II) == pred_end(*II))
231 WorkList.insert(*II);
234 // Merge pairs of basic blocks with unconditional branches, connected by
236 if (EverMadeChange || MadeChange)
237 MadeChange |= EliminateFallThrough(F);
241 EverMadeChange |= MadeChange;
244 if (ModifiedDT && DT)
247 return EverMadeChange;
250 /// EliminateFallThrough - Merge basic blocks which are connected
251 /// by a single edge, where one of the basic blocks has a single successor
252 /// pointing to the other basic block, which has a single predecessor.
253 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
254 bool Changed = false;
255 // Scan all of the blocks in the function, except for the entry block.
256 for (Function::iterator I = llvm::next(F.begin()), E = F.end(); I != E; ) {
257 BasicBlock *BB = I++;
258 // If the destination block has a single pred, then this is a trivial
259 // edge, just collapse it.
260 BasicBlock *SinglePred = BB->getSinglePredecessor();
262 // Don't merge if BB's address is taken.
263 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
265 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
266 if (Term && !Term->isConditional()) {
268 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
269 // Remember if SinglePred was the entry block of the function.
270 // If so, we will need to move BB back to the entry position.
271 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
272 MergeBasicBlockIntoOnlyPred(BB, this);
274 if (isEntry && BB != &BB->getParent()->getEntryBlock())
275 BB->moveBefore(&BB->getParent()->getEntryBlock());
277 // We have erased a block. Update the iterator.
284 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
285 /// debug info directives, and an unconditional branch. Passes before isel
286 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
287 /// isel. Start by eliminating these blocks so we can split them the way we
289 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
290 bool MadeChange = false;
291 // Note that this intentionally skips the entry block.
292 for (Function::iterator I = llvm::next(F.begin()), E = F.end(); I != E; ) {
293 BasicBlock *BB = I++;
295 // If this block doesn't end with an uncond branch, ignore it.
296 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
297 if (!BI || !BI->isUnconditional())
300 // If the instruction before the branch (skipping debug info) isn't a phi
301 // node, then other stuff is happening here.
302 BasicBlock::iterator BBI = BI;
303 if (BBI != BB->begin()) {
305 while (isa<DbgInfoIntrinsic>(BBI)) {
306 if (BBI == BB->begin())
310 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
314 // Do not break infinite loops.
315 BasicBlock *DestBB = BI->getSuccessor(0);
319 if (!CanMergeBlocks(BB, DestBB))
322 EliminateMostlyEmptyBlock(BB);
328 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
329 /// single uncond branch between them, and BB contains no other non-phi
331 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
332 const BasicBlock *DestBB) const {
333 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
334 // the successor. If there are more complex condition (e.g. preheaders),
335 // don't mess around with them.
336 BasicBlock::const_iterator BBI = BB->begin();
337 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
338 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
340 const Instruction *User = cast<Instruction>(*UI);
341 if (User->getParent() != DestBB || !isa<PHINode>(User))
343 // If User is inside DestBB block and it is a PHINode then check
344 // incoming value. If incoming value is not from BB then this is
345 // a complex condition (e.g. preheaders) we want to avoid here.
346 if (User->getParent() == DestBB) {
347 if (const PHINode *UPN = dyn_cast<PHINode>(User))
348 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
349 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
350 if (Insn && Insn->getParent() == BB &&
351 Insn->getParent() != UPN->getIncomingBlock(I))
358 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
359 // and DestBB may have conflicting incoming values for the block. If so, we
360 // can't merge the block.
361 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
362 if (!DestBBPN) return true; // no conflict.
364 // Collect the preds of BB.
365 SmallPtrSet<const BasicBlock*, 16> BBPreds;
366 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
367 // It is faster to get preds from a PHI than with pred_iterator.
368 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
369 BBPreds.insert(BBPN->getIncomingBlock(i));
371 BBPreds.insert(pred_begin(BB), pred_end(BB));
374 // Walk the preds of DestBB.
375 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
376 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
377 if (BBPreds.count(Pred)) { // Common predecessor?
378 BBI = DestBB->begin();
379 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
380 const Value *V1 = PN->getIncomingValueForBlock(Pred);
381 const Value *V2 = PN->getIncomingValueForBlock(BB);
383 // If V2 is a phi node in BB, look up what the mapped value will be.
384 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
385 if (V2PN->getParent() == BB)
386 V2 = V2PN->getIncomingValueForBlock(Pred);
388 // If there is a conflict, bail out.
389 if (V1 != V2) return false;
398 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
399 /// an unconditional branch in it.
400 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
401 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
402 BasicBlock *DestBB = BI->getSuccessor(0);
404 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
406 // If the destination block has a single pred, then this is a trivial edge,
408 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
409 if (SinglePred != DestBB) {
410 // Remember if SinglePred was the entry block of the function. If so, we
411 // will need to move BB back to the entry position.
412 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
413 MergeBasicBlockIntoOnlyPred(DestBB, this);
415 if (isEntry && BB != &BB->getParent()->getEntryBlock())
416 BB->moveBefore(&BB->getParent()->getEntryBlock());
418 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
423 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
424 // to handle the new incoming edges it is about to have.
426 for (BasicBlock::iterator BBI = DestBB->begin();
427 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
428 // Remove the incoming value for BB, and remember it.
429 Value *InVal = PN->removeIncomingValue(BB, false);
431 // Two options: either the InVal is a phi node defined in BB or it is some
432 // value that dominates BB.
433 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
434 if (InValPhi && InValPhi->getParent() == BB) {
435 // Add all of the input values of the input PHI as inputs of this phi.
436 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
437 PN->addIncoming(InValPhi->getIncomingValue(i),
438 InValPhi->getIncomingBlock(i));
440 // Otherwise, add one instance of the dominating value for each edge that
441 // we will be adding.
442 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
443 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
444 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
446 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
447 PN->addIncoming(InVal, *PI);
452 // The PHIs are now updated, change everything that refers to BB to use
453 // DestBB and remove BB.
454 BB->replaceAllUsesWith(DestBB);
455 if (DT && !ModifiedDT) {
456 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
457 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
458 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
459 DT->changeImmediateDominator(DestBB, NewIDom);
462 BB->eraseFromParent();
465 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
468 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
469 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
470 /// sink it into user blocks to reduce the number of virtual
471 /// registers that must be created and coalesced.
473 /// Return true if any changes are made.
475 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
476 // If this is a noop copy,
477 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
478 EVT DstVT = TLI.getValueType(CI->getType());
480 // This is an fp<->int conversion?
481 if (SrcVT.isInteger() != DstVT.isInteger())
484 // If this is an extension, it will be a zero or sign extension, which
486 if (SrcVT.bitsLT(DstVT)) return false;
488 // If these values will be promoted, find out what they will be promoted
489 // to. This helps us consider truncates on PPC as noop copies when they
491 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
492 TargetLowering::TypePromoteInteger)
493 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
494 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
495 TargetLowering::TypePromoteInteger)
496 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
498 // If, after promotion, these are the same types, this is a noop copy.
502 BasicBlock *DefBB = CI->getParent();
504 /// InsertedCasts - Only insert a cast in each block once.
505 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
507 bool MadeChange = false;
508 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
510 Use &TheUse = UI.getUse();
511 Instruction *User = cast<Instruction>(*UI);
513 // Figure out which BB this cast is used in. For PHI's this is the
514 // appropriate predecessor block.
515 BasicBlock *UserBB = User->getParent();
516 if (PHINode *PN = dyn_cast<PHINode>(User)) {
517 UserBB = PN->getIncomingBlock(UI);
520 // Preincrement use iterator so we don't invalidate it.
523 // If this user is in the same block as the cast, don't change the cast.
524 if (UserBB == DefBB) continue;
526 // If we have already inserted a cast into this block, use it.
527 CastInst *&InsertedCast = InsertedCasts[UserBB];
530 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
532 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
537 // Replace a use of the cast with a use of the new cast.
538 TheUse = InsertedCast;
542 // If we removed all uses, nuke the cast.
543 if (CI->use_empty()) {
544 CI->eraseFromParent();
551 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
552 /// the number of virtual registers that must be created and coalesced. This is
553 /// a clear win except on targets with multiple condition code registers
554 /// (PowerPC), where it might lose; some adjustment may be wanted there.
556 /// Return true if any changes are made.
557 static bool OptimizeCmpExpression(CmpInst *CI) {
558 BasicBlock *DefBB = CI->getParent();
560 /// InsertedCmp - Only insert a cmp in each block once.
561 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
563 bool MadeChange = false;
564 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
566 Use &TheUse = UI.getUse();
567 Instruction *User = cast<Instruction>(*UI);
569 // Preincrement use iterator so we don't invalidate it.
572 // Don't bother for PHI nodes.
573 if (isa<PHINode>(User))
576 // Figure out which BB this cmp is used in.
577 BasicBlock *UserBB = User->getParent();
579 // If this user is in the same block as the cmp, don't change the cmp.
580 if (UserBB == DefBB) continue;
582 // If we have already inserted a cmp into this block, use it.
583 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
586 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
588 CmpInst::Create(CI->getOpcode(),
589 CI->getPredicate(), CI->getOperand(0),
590 CI->getOperand(1), "", InsertPt);
594 // Replace a use of the cmp with a use of the new cmp.
595 TheUse = InsertedCmp;
599 // If we removed all uses, nuke the cmp.
601 CI->eraseFromParent();
607 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
609 void replaceCall(Value *With) {
610 CI->replaceAllUsesWith(With);
611 CI->eraseFromParent();
613 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
614 if (ConstantInt *SizeCI =
615 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
616 return SizeCI->isAllOnesValue();
620 } // end anonymous namespace
622 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
623 BasicBlock *BB = CI->getParent();
625 // Lower inline assembly if we can.
626 // If we found an inline asm expession, and if the target knows how to
627 // lower it to normal LLVM code, do so now.
628 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
629 if (TLI->ExpandInlineAsm(CI)) {
630 // Avoid invalidating the iterator.
631 CurInstIterator = BB->begin();
632 // Avoid processing instructions out of order, which could cause
633 // reuse before a value is defined.
637 // Sink address computing for memory operands into the block.
638 if (OptimizeInlineAsmInst(CI))
642 // Lower all uses of llvm.objectsize.*
643 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
644 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
645 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
646 Type *ReturnTy = CI->getType();
647 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
649 // Substituting this can cause recursive simplifications, which can
650 // invalidate our iterator. Use a WeakVH to hold onto it in case this
652 WeakVH IterHandle(CurInstIterator);
654 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
655 TLInfo, ModifiedDT ? 0 : DT);
657 // If the iterator instruction was recursively deleted, start over at the
658 // start of the block.
659 if (IterHandle != CurInstIterator) {
660 CurInstIterator = BB->begin();
667 SmallVector<Value*, 2> PtrOps;
669 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
670 while (!PtrOps.empty())
671 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
675 // From here on out we're working with named functions.
676 if (CI->getCalledFunction() == 0) return false;
678 // We'll need DataLayout from here on out.
679 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
680 if (!TD) return false;
682 // Lower all default uses of _chk calls. This is very similar
683 // to what InstCombineCalls does, but here we are only lowering calls
684 // that have the default "don't know" as the objectsize. Anything else
685 // should be left alone.
686 CodeGenPrepareFortifiedLibCalls Simplifier;
687 return Simplifier.fold(CI, TD, TLInfo);
690 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
691 /// instructions to the predecessor to enable tail call optimizations. The
692 /// case it is currently looking for is:
695 /// %tmp0 = tail call i32 @f0()
698 /// %tmp1 = tail call i32 @f1()
701 /// %tmp2 = tail call i32 @f2()
704 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
712 /// %tmp0 = tail call i32 @f0()
715 /// %tmp1 = tail call i32 @f1()
718 /// %tmp2 = tail call i32 @f2()
721 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
725 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
730 BitCastInst *BCI = 0;
731 Value *V = RI->getReturnValue();
733 BCI = dyn_cast<BitCastInst>(V);
735 V = BCI->getOperand(0);
737 PN = dyn_cast<PHINode>(V);
742 if (PN && PN->getParent() != BB)
745 // It's not safe to eliminate the sign / zero extension of the return value.
746 // See llvm::isInTailCallPosition().
747 const Function *F = BB->getParent();
748 AttributeSet CallerAttrs = F->getAttributes();
749 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
750 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
753 // Make sure there are no instructions between the PHI and return, or that the
754 // return is the first instruction in the block.
756 BasicBlock::iterator BI = BB->begin();
757 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
759 // Also skip over the bitcast.
764 BasicBlock::iterator BI = BB->begin();
765 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
770 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
772 SmallVector<CallInst*, 4> TailCalls;
774 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
775 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
776 // Make sure the phi value is indeed produced by the tail call.
777 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
778 TLI->mayBeEmittedAsTailCall(CI))
779 TailCalls.push_back(CI);
782 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
783 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
784 if (!VisitedBBs.insert(*PI))
787 BasicBlock::InstListType &InstList = (*PI)->getInstList();
788 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
789 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
790 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
794 CallInst *CI = dyn_cast<CallInst>(&*RI);
795 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
796 TailCalls.push_back(CI);
800 bool Changed = false;
801 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
802 CallInst *CI = TailCalls[i];
805 // Conservatively require the attributes of the call to match those of the
806 // return. Ignore noalias because it doesn't affect the call sequence.
807 AttributeSet CalleeAttrs = CS.getAttributes();
808 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
809 removeAttribute(Attribute::NoAlias) !=
810 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
811 removeAttribute(Attribute::NoAlias))
814 // Make sure the call instruction is followed by an unconditional branch to
816 BasicBlock *CallBB = CI->getParent();
817 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
818 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
821 // Duplicate the return into CallBB.
822 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
823 ModifiedDT = Changed = true;
827 // If we eliminated all predecessors of the block, delete the block now.
828 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
829 BB->eraseFromParent();
834 //===----------------------------------------------------------------------===//
835 // Memory Optimization
836 //===----------------------------------------------------------------------===//
840 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
841 /// which holds actual Value*'s for register values.
842 struct ExtAddrMode : public TargetLowering::AddrMode {
845 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
846 void print(raw_ostream &OS) const;
849 bool operator==(const ExtAddrMode& O) const {
850 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
851 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
852 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
857 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
863 void ExtAddrMode::print(raw_ostream &OS) const {
864 bool NeedPlus = false;
867 OS << (NeedPlus ? " + " : "")
869 BaseGV->printAsOperand(OS, /*PrintType=*/false);
874 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
877 OS << (NeedPlus ? " + " : "")
879 BaseReg->printAsOperand(OS, /*PrintType=*/false);
883 OS << (NeedPlus ? " + " : "")
885 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
891 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
892 void ExtAddrMode::dump() const {
898 /// \brief This class provides transaction based operation on the IR.
899 /// Every change made through this class is recorded in the internal state and
900 /// can be undone (rollback) until commit is called.
901 class TypePromotionTransaction {
903 /// \brief This represents the common interface of the individual transaction.
904 /// Each class implements the logic for doing one specific modification on
905 /// the IR via the TypePromotionTransaction.
906 class TypePromotionAction {
908 /// The Instruction modified.
912 /// \brief Constructor of the action.
913 /// The constructor performs the related action on the IR.
914 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
916 virtual ~TypePromotionAction() {}
918 /// \brief Undo the modification done by this action.
919 /// When this method is called, the IR must be in the same state as it was
920 /// before this action was applied.
921 /// \pre Undoing the action works if and only if the IR is in the exact same
922 /// state as it was directly after this action was applied.
923 virtual void undo() = 0;
925 /// \brief Advocate every change made by this action.
926 /// When the results on the IR of the action are to be kept, it is important
927 /// to call this function, otherwise hidden information may be kept forever.
928 virtual void commit() {
929 // Nothing to be done, this action is not doing anything.
933 /// \brief Utility to remember the position of an instruction.
934 class InsertionHandler {
935 /// Position of an instruction.
936 /// Either an instruction:
937 /// - Is the first in a basic block: BB is used.
938 /// - Has a previous instructon: PrevInst is used.
940 Instruction *PrevInst;
943 /// Remember whether or not the instruction had a previous instruction.
944 bool HasPrevInstruction;
947 /// \brief Record the position of \p Inst.
948 InsertionHandler(Instruction *Inst) {
949 BasicBlock::iterator It = Inst;
950 HasPrevInstruction = (It != (Inst->getParent()->begin()));
951 if (HasPrevInstruction)
952 Point.PrevInst = --It;
954 Point.BB = Inst->getParent();
957 /// \brief Insert \p Inst at the recorded position.
958 void insert(Instruction *Inst) {
959 if (HasPrevInstruction) {
960 if (Inst->getParent())
961 Inst->removeFromParent();
962 Inst->insertAfter(Point.PrevInst);
964 Instruction *Position = Point.BB->getFirstInsertionPt();
965 if (Inst->getParent())
966 Inst->moveBefore(Position);
968 Inst->insertBefore(Position);
973 /// \brief Move an instruction before another.
974 class InstructionMoveBefore : public TypePromotionAction {
975 /// Original position of the instruction.
976 InsertionHandler Position;
979 /// \brief Move \p Inst before \p Before.
980 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
981 : TypePromotionAction(Inst), Position(Inst) {
982 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
983 Inst->moveBefore(Before);
986 /// \brief Move the instruction back to its original position.
988 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
989 Position.insert(Inst);
993 /// \brief Set the operand of an instruction with a new value.
994 class OperandSetter : public TypePromotionAction {
995 /// Original operand of the instruction.
997 /// Index of the modified instruction.
1001 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1002 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1003 : TypePromotionAction(Inst), Idx(Idx) {
1004 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1005 << "for:" << *Inst << "\n"
1006 << "with:" << *NewVal << "\n");
1007 Origin = Inst->getOperand(Idx);
1008 Inst->setOperand(Idx, NewVal);
1011 /// \brief Restore the original value of the instruction.
1013 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1014 << "for: " << *Inst << "\n"
1015 << "with: " << *Origin << "\n");
1016 Inst->setOperand(Idx, Origin);
1020 /// \brief Hide the operands of an instruction.
1021 /// Do as if this instruction was not using any of its operands.
1022 class OperandsHider : public TypePromotionAction {
1023 /// The list of original operands.
1024 SmallVector<Value *, 4> OriginalValues;
1027 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1028 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1029 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1030 unsigned NumOpnds = Inst->getNumOperands();
1031 OriginalValues.reserve(NumOpnds);
1032 for (unsigned It = 0; It < NumOpnds; ++It) {
1033 // Save the current operand.
1034 Value *Val = Inst->getOperand(It);
1035 OriginalValues.push_back(Val);
1037 // We could use OperandSetter here, but that would implied an overhead
1038 // that we are not willing to pay.
1039 Inst->setOperand(It, UndefValue::get(Val->getType()));
1043 /// \brief Restore the original list of uses.
1045 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1046 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1047 Inst->setOperand(It, OriginalValues[It]);
1051 /// \brief Build a truncate instruction.
1052 class TruncBuilder : public TypePromotionAction {
1054 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1056 /// trunc Opnd to Ty.
1057 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1058 IRBuilder<> Builder(Opnd);
1059 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1060 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1063 /// \brief Get the built instruction.
1064 Instruction *getBuiltInstruction() { return Inst; }
1066 /// \brief Remove the built instruction.
1068 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1069 Inst->eraseFromParent();
1073 /// \brief Build a sign extension instruction.
1074 class SExtBuilder : public TypePromotionAction {
1076 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1078 /// sext Opnd to Ty.
1079 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1080 : TypePromotionAction(Inst) {
1081 IRBuilder<> Builder(InsertPt);
1082 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1083 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1086 /// \brief Get the built instruction.
1087 Instruction *getBuiltInstruction() { return Inst; }
1089 /// \brief Remove the built instruction.
1091 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1092 Inst->eraseFromParent();
1096 /// \brief Mutate an instruction to another type.
1097 class TypeMutator : public TypePromotionAction {
1098 /// Record the original type.
1102 /// \brief Mutate the type of \p Inst into \p NewTy.
1103 TypeMutator(Instruction *Inst, Type *NewTy)
1104 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1105 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1107 Inst->mutateType(NewTy);
1110 /// \brief Mutate the instruction back to its original type.
1112 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1114 Inst->mutateType(OrigTy);
1118 /// \brief Replace the uses of an instruction by another instruction.
1119 class UsesReplacer : public TypePromotionAction {
1120 /// Helper structure to keep track of the replaced uses.
1121 struct InstructionAndIdx {
1122 /// The instruction using the instruction.
1124 /// The index where this instruction is used for Inst.
1126 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1127 : Inst(Inst), Idx(Idx) {}
1130 /// Keep track of the original uses (pair Instruction, Index).
1131 SmallVector<InstructionAndIdx, 4> OriginalUses;
1132 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1135 /// \brief Replace all the use of \p Inst by \p New.
1136 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1137 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1139 // Record the original uses.
1140 for (Value::use_iterator UseIt = Inst->use_begin(),
1141 EndIt = Inst->use_end();
1142 UseIt != EndIt; ++UseIt) {
1143 Instruction *Use = cast<Instruction>(*UseIt);
1144 OriginalUses.push_back(InstructionAndIdx(Use, UseIt.getOperandNo()));
1146 // Now, we can replace the uses.
1147 Inst->replaceAllUsesWith(New);
1150 /// \brief Reassign the original uses of Inst to Inst.
1152 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1153 for (use_iterator UseIt = OriginalUses.begin(),
1154 EndIt = OriginalUses.end();
1155 UseIt != EndIt; ++UseIt) {
1156 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1161 /// \brief Remove an instruction from the IR.
1162 class InstructionRemover : public TypePromotionAction {
1163 /// Original position of the instruction.
1164 InsertionHandler Inserter;
1165 /// Helper structure to hide all the link to the instruction. In other
1166 /// words, this helps to do as if the instruction was removed.
1167 OperandsHider Hider;
1168 /// Keep track of the uses replaced, if any.
1169 UsesReplacer *Replacer;
1172 /// \brief Remove all reference of \p Inst and optinally replace all its
1174 /// \pre If !Inst->use_empty(), then New != NULL
1175 InstructionRemover(Instruction *Inst, Value *New = NULL)
1176 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1179 Replacer = new UsesReplacer(Inst, New);
1180 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1181 Inst->removeFromParent();
1184 ~InstructionRemover() { delete Replacer; }
1186 /// \brief Really remove the instruction.
1187 void commit() { delete Inst; }
1189 /// \brief Resurrect the instruction and reassign it to the proper uses if
1190 /// new value was provided when build this action.
1192 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1193 Inserter.insert(Inst);
1201 /// Restoration point.
1202 /// The restoration point is a pointer to an action instead of an iterator
1203 /// because the iterator may be invalidated but not the pointer.
1204 typedef const TypePromotionAction *ConstRestorationPt;
1205 /// Advocate every changes made in that transaction.
1207 /// Undo all the changes made after the given point.
1208 void rollback(ConstRestorationPt Point);
1209 /// Get the current restoration point.
1210 ConstRestorationPt getRestorationPoint() const;
1212 /// \name API for IR modification with state keeping to support rollback.
1214 /// Same as Instruction::setOperand.
1215 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1216 /// Same as Instruction::eraseFromParent.
1217 void eraseInstruction(Instruction *Inst, Value *NewVal = NULL);
1218 /// Same as Value::replaceAllUsesWith.
1219 void replaceAllUsesWith(Instruction *Inst, Value *New);
1220 /// Same as Value::mutateType.
1221 void mutateType(Instruction *Inst, Type *NewTy);
1222 /// Same as IRBuilder::createTrunc.
1223 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1224 /// Same as IRBuilder::createSExt.
1225 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1226 /// Same as Instruction::moveBefore.
1227 void moveBefore(Instruction *Inst, Instruction *Before);
1230 ~TypePromotionTransaction();
1233 /// The ordered list of actions made so far.
1234 SmallVector<TypePromotionAction *, 16> Actions;
1235 typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1238 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1241 new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1244 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1247 new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1250 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1252 Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1255 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1256 Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1259 Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1261 TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1262 Actions.push_back(TB);
1263 return TB->getBuiltInstruction();
1266 Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1267 Value *Opnd, Type *Ty) {
1268 SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1269 Actions.push_back(SB);
1270 return SB->getBuiltInstruction();
1273 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1274 Instruction *Before) {
1276 new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1279 TypePromotionTransaction::ConstRestorationPt
1280 TypePromotionTransaction::getRestorationPoint() const {
1281 return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : NULL;
1284 void TypePromotionTransaction::commit() {
1285 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1293 void TypePromotionTransaction::rollback(
1294 TypePromotionTransaction::ConstRestorationPt Point) {
1295 while (!Actions.empty() && Point != (*Actions.rbegin())) {
1296 TypePromotionAction *Curr = Actions.pop_back_val();
1302 TypePromotionTransaction::~TypePromotionTransaction() {
1303 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1308 /// \brief A helper class for matching addressing modes.
1310 /// This encapsulates the logic for matching the target-legal addressing modes.
1311 class AddressingModeMatcher {
1312 SmallVectorImpl<Instruction*> &AddrModeInsts;
1313 const TargetLowering &TLI;
1315 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1316 /// the memory instruction that we're computing this address for.
1318 Instruction *MemoryInst;
1320 /// AddrMode - This is the addressing mode that we're building up. This is
1321 /// part of the return value of this addressing mode matching stuff.
1322 ExtAddrMode &AddrMode;
1324 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1325 const SetOfInstrs &InsertedTruncs;
1326 /// A map from the instructions to their type before promotion.
1327 InstrToOrigTy &PromotedInsts;
1328 /// The ongoing transaction where every action should be registered.
1329 TypePromotionTransaction &TPT;
1331 /// IgnoreProfitability - This is set to true when we should not do
1332 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1333 /// always returns true.
1334 bool IgnoreProfitability;
1336 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1337 const TargetLowering &T, Type *AT,
1338 Instruction *MI, ExtAddrMode &AM,
1339 const SetOfInstrs &InsertedTruncs,
1340 InstrToOrigTy &PromotedInsts,
1341 TypePromotionTransaction &TPT)
1342 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1343 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1344 IgnoreProfitability = false;
1348 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1349 /// give an access type of AccessTy. This returns a list of involved
1350 /// instructions in AddrModeInsts.
1351 /// \p InsertedTruncs The truncate instruction inserted by other
1354 /// \p PromotedInsts maps the instructions to their type before promotion.
1355 /// \p The ongoing transaction where every action should be registered.
1356 static ExtAddrMode Match(Value *V, Type *AccessTy,
1357 Instruction *MemoryInst,
1358 SmallVectorImpl<Instruction*> &AddrModeInsts,
1359 const TargetLowering &TLI,
1360 const SetOfInstrs &InsertedTruncs,
1361 InstrToOrigTy &PromotedInsts,
1362 TypePromotionTransaction &TPT) {
1365 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1366 MemoryInst, Result, InsertedTruncs,
1367 PromotedInsts, TPT).MatchAddr(V, 0);
1368 (void)Success; assert(Success && "Couldn't select *anything*?");
1372 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1373 bool MatchAddr(Value *V, unsigned Depth);
1374 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1375 bool *MovedAway = NULL);
1376 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1377 ExtAddrMode &AMBefore,
1378 ExtAddrMode &AMAfter);
1379 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1380 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1381 Value *PromotedOperand) const;
1384 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1385 /// Return true and update AddrMode if this addr mode is legal for the target,
1387 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1389 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1390 // mode. Just process that directly.
1392 return MatchAddr(ScaleReg, Depth);
1394 // If the scale is 0, it takes nothing to add this.
1398 // If we already have a scale of this value, we can add to it, otherwise, we
1399 // need an available scale field.
1400 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1403 ExtAddrMode TestAddrMode = AddrMode;
1405 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1406 // [A+B + A*7] -> [B+A*8].
1407 TestAddrMode.Scale += Scale;
1408 TestAddrMode.ScaledReg = ScaleReg;
1410 // If the new address isn't legal, bail out.
1411 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1414 // It was legal, so commit it.
1415 AddrMode = TestAddrMode;
1417 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1418 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1419 // X*Scale + C*Scale to addr mode.
1420 ConstantInt *CI = 0; Value *AddLHS = 0;
1421 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1422 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1423 TestAddrMode.ScaledReg = AddLHS;
1424 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1426 // If this addressing mode is legal, commit it and remember that we folded
1427 // this instruction.
1428 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1429 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1430 AddrMode = TestAddrMode;
1435 // Otherwise, not (x+c)*scale, just return what we have.
1439 /// MightBeFoldableInst - This is a little filter, which returns true if an
1440 /// addressing computation involving I might be folded into a load/store
1441 /// accessing it. This doesn't need to be perfect, but needs to accept at least
1442 /// the set of instructions that MatchOperationAddr can.
1443 static bool MightBeFoldableInst(Instruction *I) {
1444 switch (I->getOpcode()) {
1445 case Instruction::BitCast:
1446 // Don't touch identity bitcasts.
1447 if (I->getType() == I->getOperand(0)->getType())
1449 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1450 case Instruction::PtrToInt:
1451 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1453 case Instruction::IntToPtr:
1454 // We know the input is intptr_t, so this is foldable.
1456 case Instruction::Add:
1458 case Instruction::Mul:
1459 case Instruction::Shl:
1460 // Can only handle X*C and X << C.
1461 return isa<ConstantInt>(I->getOperand(1));
1462 case Instruction::GetElementPtr:
1469 /// \brief Hepler class to perform type promotion.
1470 class TypePromotionHelper {
1471 /// \brief Utility function to check whether or not a sign extension of
1472 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1473 /// using the operands of \p Inst or promoting \p Inst.
1474 /// In other words, check if:
1475 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1476 /// #1 Promotion applies:
1477 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1478 /// #2 Operand reuses:
1479 /// sext opnd1 to ConsideredSExtType.
1480 /// \p PromotedInsts maps the instructions to their type before promotion.
1481 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1482 const InstrToOrigTy &PromotedInsts);
1484 /// \brief Utility function to determine if \p OpIdx should be promoted when
1485 /// promoting \p Inst.
1486 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1487 if (isa<SelectInst>(Inst) && OpIdx == 0)
1492 /// \brief Utility function to promote the operand of \p SExt when this
1493 /// operand is a promotable trunc or sext.
1494 /// \p PromotedInsts maps the instructions to their type before promotion.
1495 /// \p CreatedInsts[out] contains how many non-free instructions have been
1496 /// created to promote the operand of SExt.
1497 /// Should never be called directly.
1498 /// \return The promoted value which is used instead of SExt.
1499 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1500 TypePromotionTransaction &TPT,
1501 InstrToOrigTy &PromotedInsts,
1502 unsigned &CreatedInsts);
1504 /// \brief Utility function to promote the operand of \p SExt when this
1505 /// operand is promotable and is not a supported trunc or sext.
1506 /// \p PromotedInsts maps the instructions to their type before promotion.
1507 /// \p CreatedInsts[out] contains how many non-free instructions have been
1508 /// created to promote the operand of SExt.
1509 /// Should never be called directly.
1510 /// \return The promoted value which is used instead of SExt.
1511 static Value *promoteOperandForOther(Instruction *SExt,
1512 TypePromotionTransaction &TPT,
1513 InstrToOrigTy &PromotedInsts,
1514 unsigned &CreatedInsts);
1517 /// Type for the utility function that promotes the operand of SExt.
1518 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1519 InstrToOrigTy &PromotedInsts,
1520 unsigned &CreatedInsts);
1521 /// \brief Given a sign extend instruction \p SExt, return the approriate
1522 /// action to promote the operand of \p SExt instead of using SExt.
1523 /// \return NULL if no promotable action is possible with the current
1525 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1526 /// the others CodeGenPrepare optimizations. This information is important
1527 /// because we do not want to promote these instructions as CodeGenPrepare
1528 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1529 /// \p PromotedInsts maps the instructions to their type before promotion.
1530 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1531 const TargetLowering &TLI,
1532 const InstrToOrigTy &PromotedInsts);
1535 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1536 Type *ConsideredSExtType,
1537 const InstrToOrigTy &PromotedInsts) {
1538 // We can always get through sext.
1539 if (isa<SExtInst>(Inst))
1542 // We can get through binary operator, if it is legal. In other words, the
1543 // binary operator must have a nuw or nsw flag.
1544 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1545 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1546 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1549 // Check if we can do the following simplification.
1550 // sext(trunc(sext)) --> sext
1551 if (!isa<TruncInst>(Inst))
1554 Value *OpndVal = Inst->getOperand(0);
1555 // Check if we can use this operand in the sext.
1556 // If the type is larger than the result type of the sign extension,
1558 if (OpndVal->getType()->getIntegerBitWidth() >
1559 ConsideredSExtType->getIntegerBitWidth())
1562 // If the operand of the truncate is not an instruction, we will not have
1563 // any information on the dropped bits.
1564 // (Actually we could for constant but it is not worth the extra logic).
1565 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1569 // Check if the source of the type is narrow enough.
1570 // I.e., check that trunc just drops sign extended bits.
1571 // #1 get the type of the operand.
1572 const Type *OpndType;
1573 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1574 if (It != PromotedInsts.end())
1575 OpndType = It->second;
1576 else if (isa<SExtInst>(Opnd))
1577 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1581 // #2 check that the truncate just drop sign extended bits.
1582 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1588 TypePromotionHelper::Action TypePromotionHelper::getAction(
1589 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1590 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1591 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1592 Type *SExtTy = SExt->getType();
1593 // If the operand of the sign extension is not an instruction, we cannot
1595 // If it, check we can get through.
1596 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1599 // Do not promote if the operand has been added by codegenprepare.
1600 // Otherwise, it means we are undoing an optimization that is likely to be
1601 // redone, thus causing potential infinite loop.
1602 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1605 // SExt or Trunc instructions.
1606 // Return the related handler.
1607 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1608 return promoteOperandForTruncAndSExt;
1610 // Regular instruction.
1611 // Abort early if we will have to insert non-free instructions.
1612 if (!SExtOpnd->hasOneUse() &&
1613 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1615 return promoteOperandForOther;
1618 Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1619 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1620 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1621 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1622 // get through it and this method should not be called.
1623 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1624 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1626 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1629 // Remove dead code.
1630 if (SExtOpnd->use_empty())
1631 TPT.eraseInstruction(SExtOpnd);
1633 // Check if the sext is still needed.
1634 if (SExt->getType() != SExt->getOperand(0)->getType())
1637 // At this point we have: sext ty opnd to ty.
1638 // Reassign the uses of SExt to the opnd and remove SExt.
1639 Value *NextVal = SExt->getOperand(0);
1640 TPT.eraseInstruction(SExt, NextVal);
1645 TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1646 TypePromotionTransaction &TPT,
1647 InstrToOrigTy &PromotedInsts,
1648 unsigned &CreatedInsts) {
1649 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1650 // get through it and this method should not be called.
1651 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1653 if (!SExtOpnd->hasOneUse()) {
1654 // SExtOpnd will be promoted.
1655 // All its uses, but SExt, will need to use a truncated value of the
1656 // promoted version.
1657 // Create the truncate now.
1658 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1659 Trunc->removeFromParent();
1660 // Insert it just after the definition.
1661 Trunc->insertAfter(SExtOpnd);
1663 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1664 // Restore the operand of SExt (which has been replace by the previous call
1665 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1666 TPT.setOperand(SExt, 0, SExtOpnd);
1669 // Get through the Instruction:
1670 // 1. Update its type.
1671 // 2. Replace the uses of SExt by Inst.
1672 // 3. Sign extend each operand that needs to be sign extended.
1674 // Remember the original type of the instruction before promotion.
1675 // This is useful to know that the high bits are sign extended bits.
1676 PromotedInsts.insert(
1677 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1679 TPT.mutateType(SExtOpnd, SExt->getType());
1681 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1683 Instruction *SExtForOpnd = SExt;
1685 DEBUG(dbgs() << "Propagate SExt to operands\n");
1686 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1688 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1689 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1690 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1691 DEBUG(dbgs() << "No need to propagate\n");
1694 // Check if we can statically sign extend the operand.
1695 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1696 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1697 DEBUG(dbgs() << "Statically sign extend\n");
1700 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1703 // UndefValue are typed, so we have to statically sign extend them.
1704 if (isa<UndefValue>(Opnd)) {
1705 DEBUG(dbgs() << "Statically sign extend\n");
1706 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1710 // Otherwise we have to explicity sign extend the operand.
1711 // Check if SExt was reused to sign extend an operand.
1713 // If yes, create a new one.
1714 DEBUG(dbgs() << "More operands to sext\n");
1715 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1719 TPT.setOperand(SExtForOpnd, 0, Opnd);
1721 // Move the sign extension before the insertion point.
1722 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1723 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1724 // If more sext are required, new instructions will have to be created.
1727 if (SExtForOpnd == SExt) {
1728 DEBUG(dbgs() << "Sign extension is useless now\n");
1729 TPT.eraseInstruction(SExt);
1734 /// IsPromotionProfitable - Check whether or not promoting an instruction
1735 /// to a wider type was profitable.
1736 /// \p MatchedSize gives the number of instructions that have been matched
1737 /// in the addressing mode after the promotion was applied.
1738 /// \p SizeWithPromotion gives the number of created instructions for
1739 /// the promotion plus the number of instructions that have been
1740 /// matched in the addressing mode before the promotion.
1741 /// \p PromotedOperand is the value that has been promoted.
1742 /// \return True if the promotion is profitable, false otherwise.
1744 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1745 unsigned SizeWithPromotion,
1746 Value *PromotedOperand) const {
1747 // We folded less instructions than what we created to promote the operand.
1748 // This is not profitable.
1749 if (MatchedSize < SizeWithPromotion)
1751 if (MatchedSize > SizeWithPromotion)
1753 // The promotion is neutral but it may help folding the sign extension in
1754 // loads for instance.
1755 // Check that we did not create an illegal instruction.
1756 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1759 return TLI.isOperationLegalOrCustom(PromotedInst->getOpcode(),
1760 EVT::getEVT(PromotedInst->getType()));
1763 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
1764 /// fold the operation into the addressing mode. If so, update the addressing
1765 /// mode and return true, otherwise return false without modifying AddrMode.
1766 /// If \p MovedAway is not NULL, it contains the information of whether or
1767 /// not AddrInst has to be folded into the addressing mode on success.
1768 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1769 /// because it has been moved away.
1770 /// Thus AddrInst must not be added in the matched instructions.
1771 /// This state can happen when AddrInst is a sext, since it may be moved away.
1772 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
1773 /// not be referenced anymore.
1774 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1777 // Avoid exponential behavior on extremely deep expression trees.
1778 if (Depth >= 5) return false;
1780 // By default, all matched instructions stay in place.
1785 case Instruction::PtrToInt:
1786 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1787 return MatchAddr(AddrInst->getOperand(0), Depth);
1788 case Instruction::IntToPtr:
1789 // This inttoptr is a no-op if the integer type is pointer sized.
1790 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
1791 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
1792 return MatchAddr(AddrInst->getOperand(0), Depth);
1794 case Instruction::BitCast:
1795 // BitCast is always a noop, and we can handle it as long as it is
1796 // int->int or pointer->pointer (we don't want int<->fp or something).
1797 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1798 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1799 // Don't touch identity bitcasts. These were probably put here by LSR,
1800 // and we don't want to mess around with them. Assume it knows what it
1802 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1803 return MatchAddr(AddrInst->getOperand(0), Depth);
1805 case Instruction::Add: {
1806 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1807 ExtAddrMode BackupAddrMode = AddrMode;
1808 unsigned OldSize = AddrModeInsts.size();
1809 // Start a transaction at this point.
1810 // The LHS may match but not the RHS.
1811 // Therefore, we need a higher level restoration point to undo partially
1812 // matched operation.
1813 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1814 TPT.getRestorationPoint();
1816 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1817 MatchAddr(AddrInst->getOperand(0), Depth+1))
1820 // Restore the old addr mode info.
1821 AddrMode = BackupAddrMode;
1822 AddrModeInsts.resize(OldSize);
1823 TPT.rollback(LastKnownGood);
1825 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1826 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1827 MatchAddr(AddrInst->getOperand(1), Depth+1))
1830 // Otherwise we definitely can't merge the ADD in.
1831 AddrMode = BackupAddrMode;
1832 AddrModeInsts.resize(OldSize);
1833 TPT.rollback(LastKnownGood);
1836 //case Instruction::Or:
1837 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1839 case Instruction::Mul:
1840 case Instruction::Shl: {
1841 // Can only handle X*C and X << C.
1842 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1843 if (!RHS) return false;
1844 int64_t Scale = RHS->getSExtValue();
1845 if (Opcode == Instruction::Shl)
1846 Scale = 1LL << Scale;
1848 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1850 case Instruction::GetElementPtr: {
1851 // Scan the GEP. We check it if it contains constant offsets and at most
1852 // one variable offset.
1853 int VariableOperand = -1;
1854 unsigned VariableScale = 0;
1856 int64_t ConstantOffset = 0;
1857 const DataLayout *TD = TLI.getDataLayout();
1858 gep_type_iterator GTI = gep_type_begin(AddrInst);
1859 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1860 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1861 const StructLayout *SL = TD->getStructLayout(STy);
1863 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1864 ConstantOffset += SL->getElementOffset(Idx);
1866 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1867 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1868 ConstantOffset += CI->getSExtValue()*TypeSize;
1869 } else if (TypeSize) { // Scales of zero don't do anything.
1870 // We only allow one variable index at the moment.
1871 if (VariableOperand != -1)
1874 // Remember the variable index.
1875 VariableOperand = i;
1876 VariableScale = TypeSize;
1881 // A common case is for the GEP to only do a constant offset. In this case,
1882 // just add it to the disp field and check validity.
1883 if (VariableOperand == -1) {
1884 AddrMode.BaseOffs += ConstantOffset;
1885 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1886 // Check to see if we can fold the base pointer in too.
1887 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1890 AddrMode.BaseOffs -= ConstantOffset;
1894 // Save the valid addressing mode in case we can't match.
1895 ExtAddrMode BackupAddrMode = AddrMode;
1896 unsigned OldSize = AddrModeInsts.size();
1898 // See if the scale and offset amount is valid for this target.
1899 AddrMode.BaseOffs += ConstantOffset;
1901 // Match the base operand of the GEP.
1902 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1903 // If it couldn't be matched, just stuff the value in a register.
1904 if (AddrMode.HasBaseReg) {
1905 AddrMode = BackupAddrMode;
1906 AddrModeInsts.resize(OldSize);
1909 AddrMode.HasBaseReg = true;
1910 AddrMode.BaseReg = AddrInst->getOperand(0);
1913 // Match the remaining variable portion of the GEP.
1914 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1916 // If it couldn't be matched, try stuffing the base into a register
1917 // instead of matching it, and retrying the match of the scale.
1918 AddrMode = BackupAddrMode;
1919 AddrModeInsts.resize(OldSize);
1920 if (AddrMode.HasBaseReg)
1922 AddrMode.HasBaseReg = true;
1923 AddrMode.BaseReg = AddrInst->getOperand(0);
1924 AddrMode.BaseOffs += ConstantOffset;
1925 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1926 VariableScale, Depth)) {
1927 // If even that didn't work, bail.
1928 AddrMode = BackupAddrMode;
1929 AddrModeInsts.resize(OldSize);
1936 case Instruction::SExt: {
1937 // Try to move this sext out of the way of the addressing mode.
1938 Instruction *SExt = cast<Instruction>(AddrInst);
1939 // Ask for a method for doing so.
1940 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1941 SExt, InsertedTruncs, TLI, PromotedInsts);
1945 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1946 TPT.getRestorationPoint();
1947 unsigned CreatedInsts = 0;
1948 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1949 // SExt has been moved away.
1950 // Thus either it will be rematched later in the recursive calls or it is
1951 // gone. Anyway, we must not fold it into the addressing mode at this point.
1955 // addr = gep base, idx
1957 // promotedOpnd = sext opnd <- no match here
1958 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
1959 // addr = gep base, op <- match
1963 assert(PromotedOperand &&
1964 "TypePromotionHelper should have filtered out those cases");
1966 ExtAddrMode BackupAddrMode = AddrMode;
1967 unsigned OldSize = AddrModeInsts.size();
1969 if (!MatchAddr(PromotedOperand, Depth) ||
1970 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
1972 AddrMode = BackupAddrMode;
1973 AddrModeInsts.resize(OldSize);
1974 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
1975 TPT.rollback(LastKnownGood);
1984 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
1985 /// addressing mode. If Addr can't be added to AddrMode this returns false and
1986 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
1987 /// or intptr_t for the target.
1989 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
1990 // Start a transaction at this point that we will rollback if the matching
1992 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1993 TPT.getRestorationPoint();
1994 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
1995 // Fold in immediates if legal for the target.
1996 AddrMode.BaseOffs += CI->getSExtValue();
1997 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1999 AddrMode.BaseOffs -= CI->getSExtValue();
2000 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2001 // If this is a global variable, try to fold it into the addressing mode.
2002 if (AddrMode.BaseGV == 0) {
2003 AddrMode.BaseGV = GV;
2004 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2006 AddrMode.BaseGV = 0;
2008 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2009 ExtAddrMode BackupAddrMode = AddrMode;
2010 unsigned OldSize = AddrModeInsts.size();
2012 // Check to see if it is possible to fold this operation.
2013 bool MovedAway = false;
2014 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2015 // This instruction may have been move away. If so, there is nothing
2019 // Okay, it's possible to fold this. Check to see if it is actually
2020 // *profitable* to do so. We use a simple cost model to avoid increasing
2021 // register pressure too much.
2022 if (I->hasOneUse() ||
2023 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2024 AddrModeInsts.push_back(I);
2028 // It isn't profitable to do this, roll back.
2029 //cerr << "NOT FOLDING: " << *I;
2030 AddrMode = BackupAddrMode;
2031 AddrModeInsts.resize(OldSize);
2032 TPT.rollback(LastKnownGood);
2034 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2035 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2037 TPT.rollback(LastKnownGood);
2038 } else if (isa<ConstantPointerNull>(Addr)) {
2039 // Null pointer gets folded without affecting the addressing mode.
2043 // Worse case, the target should support [reg] addressing modes. :)
2044 if (!AddrMode.HasBaseReg) {
2045 AddrMode.HasBaseReg = true;
2046 AddrMode.BaseReg = Addr;
2047 // Still check for legality in case the target supports [imm] but not [i+r].
2048 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2050 AddrMode.HasBaseReg = false;
2051 AddrMode.BaseReg = 0;
2054 // If the base register is already taken, see if we can do [r+r].
2055 if (AddrMode.Scale == 0) {
2057 AddrMode.ScaledReg = Addr;
2058 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2061 AddrMode.ScaledReg = 0;
2064 TPT.rollback(LastKnownGood);
2068 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2069 /// inline asm call are due to memory operands. If so, return true, otherwise
2071 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2072 const TargetLowering &TLI) {
2073 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2074 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2075 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2077 // Compute the constraint code and ConstraintType to use.
2078 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2080 // If this asm operand is our Value*, and if it isn't an indirect memory
2081 // operand, we can't fold it!
2082 if (OpInfo.CallOperandVal == OpVal &&
2083 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2084 !OpInfo.isIndirect))
2091 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2092 /// memory use. If we find an obviously non-foldable instruction, return true.
2093 /// Add the ultimately found memory instructions to MemoryUses.
2094 static bool FindAllMemoryUses(Instruction *I,
2095 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2096 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2097 const TargetLowering &TLI) {
2098 // If we already considered this instruction, we're done.
2099 if (!ConsideredInsts.insert(I))
2102 // If this is an obviously unfoldable instruction, bail out.
2103 if (!MightBeFoldableInst(I))
2106 // Loop over all the uses, recursively processing them.
2107 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2111 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2112 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
2116 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2117 unsigned opNo = UI.getOperandNo();
2118 if (opNo == 0) return true; // Storing addr, not into addr.
2119 MemoryUses.push_back(std::make_pair(SI, opNo));
2123 if (CallInst *CI = dyn_cast<CallInst>(U)) {
2124 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2125 if (!IA) return true;
2127 // If this is a memory operand, we're cool, otherwise bail out.
2128 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2133 if (FindAllMemoryUses(cast<Instruction>(U), MemoryUses, ConsideredInsts,
2141 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2142 /// the use site that we're folding it into. If so, there is no cost to
2143 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2144 /// that we know are live at the instruction already.
2145 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2146 Value *KnownLive2) {
2147 // If Val is either of the known-live values, we know it is live!
2148 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
2151 // All values other than instructions and arguments (e.g. constants) are live.
2152 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2154 // If Val is a constant sized alloca in the entry block, it is live, this is
2155 // true because it is just a reference to the stack/frame pointer, which is
2156 // live for the whole function.
2157 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2158 if (AI->isStaticAlloca())
2161 // Check to see if this value is already used in the memory instruction's
2162 // block. If so, it's already live into the block at the very least, so we
2163 // can reasonably fold it.
2164 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2167 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2168 /// mode of the machine to fold the specified instruction into a load or store
2169 /// that ultimately uses it. However, the specified instruction has multiple
2170 /// uses. Given this, it may actually increase register pressure to fold it
2171 /// into the load. For example, consider this code:
2175 /// use(Y) -> nonload/store
2179 /// In this case, Y has multiple uses, and can be folded into the load of Z
2180 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2181 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2182 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2183 /// number of computations either.
2185 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2186 /// X was live across 'load Z' for other reasons, we actually *would* want to
2187 /// fold the addressing mode in the Z case. This would make Y die earlier.
2188 bool AddressingModeMatcher::
2189 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2190 ExtAddrMode &AMAfter) {
2191 if (IgnoreProfitability) return true;
2193 // AMBefore is the addressing mode before this instruction was folded into it,
2194 // and AMAfter is the addressing mode after the instruction was folded. Get
2195 // the set of registers referenced by AMAfter and subtract out those
2196 // referenced by AMBefore: this is the set of values which folding in this
2197 // address extends the lifetime of.
2199 // Note that there are only two potential values being referenced here,
2200 // BaseReg and ScaleReg (global addresses are always available, as are any
2201 // folded immediates).
2202 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2204 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2205 // lifetime wasn't extended by adding this instruction.
2206 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2208 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2211 // If folding this instruction (and it's subexprs) didn't extend any live
2212 // ranges, we're ok with it.
2213 if (BaseReg == 0 && ScaledReg == 0)
2216 // If all uses of this instruction are ultimately load/store/inlineasm's,
2217 // check to see if their addressing modes will include this instruction. If
2218 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2220 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2221 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2222 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2223 return false; // Has a non-memory, non-foldable use!
2225 // Now that we know that all uses of this instruction are part of a chain of
2226 // computation involving only operations that could theoretically be folded
2227 // into a memory use, loop over each of these uses and see if they could
2228 // *actually* fold the instruction.
2229 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2230 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2231 Instruction *User = MemoryUses[i].first;
2232 unsigned OpNo = MemoryUses[i].second;
2234 // Get the access type of this use. If the use isn't a pointer, we don't
2235 // know what it accesses.
2236 Value *Address = User->getOperand(OpNo);
2237 if (!Address->getType()->isPointerTy())
2239 Type *AddressAccessTy = Address->getType()->getPointerElementType();
2241 // Do a match against the root of this address, ignoring profitability. This
2242 // will tell us if the addressing mode for the memory operation will
2243 // *actually* cover the shared instruction.
2245 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2246 TPT.getRestorationPoint();
2247 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2248 MemoryInst, Result, InsertedTruncs,
2249 PromotedInsts, TPT);
2250 Matcher.IgnoreProfitability = true;
2251 bool Success = Matcher.MatchAddr(Address, 0);
2252 (void)Success; assert(Success && "Couldn't select *anything*?");
2254 // The match was to check the profitability, the changes made are not
2255 // part of the original matcher. Therefore, they should be dropped
2256 // otherwise the original matcher will not present the right state.
2257 TPT.rollback(LastKnownGood);
2259 // If the match didn't cover I, then it won't be shared by it.
2260 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2261 I) == MatchedAddrModeInsts.end())
2264 MatchedAddrModeInsts.clear();
2270 } // end anonymous namespace
2272 /// IsNonLocalValue - Return true if the specified values are defined in a
2273 /// different basic block than BB.
2274 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2275 if (Instruction *I = dyn_cast<Instruction>(V))
2276 return I->getParent() != BB;
2280 /// OptimizeMemoryInst - Load and Store Instructions often have
2281 /// addressing modes that can do significant amounts of computation. As such,
2282 /// instruction selection will try to get the load or store to do as much
2283 /// computation as possible for the program. The problem is that isel can only
2284 /// see within a single block. As such, we sink as much legal addressing mode
2285 /// stuff into the block as possible.
2287 /// This method is used to optimize both load/store and inline asms with memory
2289 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2293 // Try to collapse single-value PHI nodes. This is necessary to undo
2294 // unprofitable PRE transformations.
2295 SmallVector<Value*, 8> worklist;
2296 SmallPtrSet<Value*, 16> Visited;
2297 worklist.push_back(Addr);
2299 // Use a worklist to iteratively look through PHI nodes, and ensure that
2300 // the addressing mode obtained from the non-PHI roots of the graph
2302 Value *Consensus = 0;
2303 unsigned NumUsesConsensus = 0;
2304 bool IsNumUsesConsensusValid = false;
2305 SmallVector<Instruction*, 16> AddrModeInsts;
2306 ExtAddrMode AddrMode;
2307 TypePromotionTransaction TPT;
2308 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2309 TPT.getRestorationPoint();
2310 while (!worklist.empty()) {
2311 Value *V = worklist.back();
2312 worklist.pop_back();
2314 // Break use-def graph loops.
2315 if (!Visited.insert(V)) {
2320 // For a PHI node, push all of its incoming values.
2321 if (PHINode *P = dyn_cast<PHINode>(V)) {
2322 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2323 worklist.push_back(P->getIncomingValue(i));
2327 // For non-PHIs, determine the addressing mode being computed.
2328 SmallVector<Instruction*, 16> NewAddrModeInsts;
2329 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2330 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2331 PromotedInsts, TPT);
2333 // This check is broken into two cases with very similar code to avoid using
2334 // getNumUses() as much as possible. Some values have a lot of uses, so
2335 // calling getNumUses() unconditionally caused a significant compile-time
2339 AddrMode = NewAddrMode;
2340 AddrModeInsts = NewAddrModeInsts;
2342 } else if (NewAddrMode == AddrMode) {
2343 if (!IsNumUsesConsensusValid) {
2344 NumUsesConsensus = Consensus->getNumUses();
2345 IsNumUsesConsensusValid = true;
2348 // Ensure that the obtained addressing mode is equivalent to that obtained
2349 // for all other roots of the PHI traversal. Also, when choosing one
2350 // such root as representative, select the one with the most uses in order
2351 // to keep the cost modeling heuristics in AddressingModeMatcher
2353 unsigned NumUses = V->getNumUses();
2354 if (NumUses > NumUsesConsensus) {
2356 NumUsesConsensus = NumUses;
2357 AddrModeInsts = NewAddrModeInsts;
2366 // If the addressing mode couldn't be determined, or if multiple different
2367 // ones were determined, bail out now.
2369 TPT.rollback(LastKnownGood);
2374 // Check to see if any of the instructions supersumed by this addr mode are
2375 // non-local to I's BB.
2376 bool AnyNonLocal = false;
2377 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2378 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2384 // If all the instructions matched are already in this BB, don't do anything.
2386 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
2390 // Insert this computation right after this user. Since our caller is
2391 // scanning from the top of the BB to the bottom, reuse of the expr are
2392 // guaranteed to happen later.
2393 IRBuilder<> Builder(MemoryInst);
2395 // Now that we determined the addressing expression we want to use and know
2396 // that we have to sink it into this block. Check to see if we have already
2397 // done this for some other load/store instr in this block. If so, reuse the
2399 Value *&SunkAddr = SunkAddrs[Addr];
2401 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2403 if (SunkAddr->getType() != Addr->getType())
2404 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2406 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2408 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2411 // Start with the base register. Do this first so that subsequent address
2412 // matching finds it last, which will prevent it from trying to match it
2413 // as the scaled value in case it happens to be a mul. That would be
2414 // problematic if we've sunk a different mul for the scale, because then
2415 // we'd end up sinking both muls.
2416 if (AddrMode.BaseReg) {
2417 Value *V = AddrMode.BaseReg;
2418 if (V->getType()->isPointerTy())
2419 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2420 if (V->getType() != IntPtrTy)
2421 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2425 // Add the scale value.
2426 if (AddrMode.Scale) {
2427 Value *V = AddrMode.ScaledReg;
2428 if (V->getType() == IntPtrTy) {
2430 } else if (V->getType()->isPointerTy()) {
2431 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2432 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2433 cast<IntegerType>(V->getType())->getBitWidth()) {
2434 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2436 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
2438 if (AddrMode.Scale != 1)
2439 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2442 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2447 // Add in the BaseGV if present.
2448 if (AddrMode.BaseGV) {
2449 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2451 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2456 // Add in the Base Offset if present.
2457 if (AddrMode.BaseOffs) {
2458 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2460 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2466 SunkAddr = Constant::getNullValue(Addr->getType());
2468 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2471 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2473 // If we have no uses, recursively delete the value and all dead instructions
2475 if (Repl->use_empty()) {
2476 // This can cause recursive deletion, which can invalidate our iterator.
2477 // Use a WeakVH to hold onto it in case this happens.
2478 WeakVH IterHandle(CurInstIterator);
2479 BasicBlock *BB = CurInstIterator->getParent();
2481 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2483 if (IterHandle != CurInstIterator) {
2484 // If the iterator instruction was recursively deleted, start over at the
2485 // start of the block.
2486 CurInstIterator = BB->begin();
2494 /// OptimizeInlineAsmInst - If there are any memory operands, use
2495 /// OptimizeMemoryInst to sink their address computing into the block when
2496 /// possible / profitable.
2497 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2498 bool MadeChange = false;
2500 TargetLowering::AsmOperandInfoVector
2501 TargetConstraints = TLI->ParseConstraints(CS);
2503 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2504 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2506 // Compute the constraint code and ConstraintType to use.
2507 TLI->ComputeConstraintToUse(OpInfo, SDValue());
2509 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2510 OpInfo.isIndirect) {
2511 Value *OpVal = CS->getArgOperand(ArgNo++);
2512 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2513 } else if (OpInfo.Type == InlineAsm::isInput)
2520 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2521 /// basic block as the load, unless conditions are unfavorable. This allows
2522 /// SelectionDAG to fold the extend into the load.
2524 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2525 // Look for a load being extended.
2526 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2527 if (!LI) return false;
2529 // If they're already in the same block, there's nothing to do.
2530 if (LI->getParent() == I->getParent())
2533 // If the load has other users and the truncate is not free, this probably
2534 // isn't worthwhile.
2535 if (!LI->hasOneUse() &&
2536 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2537 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
2538 !TLI->isTruncateFree(I->getType(), LI->getType()))
2541 // Check whether the target supports casts folded into loads.
2543 if (isa<ZExtInst>(I))
2544 LType = ISD::ZEXTLOAD;
2546 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2547 LType = ISD::SEXTLOAD;
2549 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
2552 // Move the extend into the same block as the load, so that SelectionDAG
2554 I->removeFromParent();
2560 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2561 BasicBlock *DefBB = I->getParent();
2563 // If the result of a {s|z}ext and its source are both live out, rewrite all
2564 // other uses of the source with result of extension.
2565 Value *Src = I->getOperand(0);
2566 if (Src->hasOneUse())
2569 // Only do this xform if truncating is free.
2570 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
2573 // Only safe to perform the optimization if the source is also defined in
2575 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
2578 bool DefIsLiveOut = false;
2579 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2581 Instruction *User = cast<Instruction>(*UI);
2583 // Figure out which BB this ext is used in.
2584 BasicBlock *UserBB = User->getParent();
2585 if (UserBB == DefBB) continue;
2586 DefIsLiveOut = true;
2592 // Make sure none of the uses are PHI nodes.
2593 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
2595 Instruction *User = cast<Instruction>(*UI);
2596 BasicBlock *UserBB = User->getParent();
2597 if (UserBB == DefBB) continue;
2598 // Be conservative. We don't want this xform to end up introducing
2599 // reloads just before load / store instructions.
2600 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
2604 // InsertedTruncs - Only insert one trunc in each block once.
2605 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2607 bool MadeChange = false;
2608 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
2610 Use &TheUse = UI.getUse();
2611 Instruction *User = cast<Instruction>(*UI);
2613 // Figure out which BB this ext is used in.
2614 BasicBlock *UserBB = User->getParent();
2615 if (UserBB == DefBB) continue;
2617 // Both src and def are live in this block. Rewrite the use.
2618 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2620 if (!InsertedTrunc) {
2621 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2622 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
2623 InsertedTruncsSet.insert(InsertedTrunc);
2626 // Replace a use of the {s|z}ext source with a use of the result.
2627 TheUse = InsertedTrunc;
2635 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2636 /// turned into an explicit branch.
2637 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2638 // FIXME: This should use the same heuristics as IfConversion to determine
2639 // whether a select is better represented as a branch. This requires that
2640 // branch probability metadata is preserved for the select, which is not the
2643 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2645 // If the branch is predicted right, an out of order CPU can avoid blocking on
2646 // the compare. Emit cmovs on compares with a memory operand as branches to
2647 // avoid stalls on the load from memory. If the compare has more than one use
2648 // there's probably another cmov or setcc around so it's not worth emitting a
2653 Value *CmpOp0 = Cmp->getOperand(0);
2654 Value *CmpOp1 = Cmp->getOperand(1);
2656 // We check that the memory operand has one use to avoid uses of the loaded
2657 // value directly after the compare, making branches unprofitable.
2658 return Cmp->hasOneUse() &&
2659 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2660 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2664 /// If we have a SelectInst that will likely profit from branch prediction,
2665 /// turn it into a branch.
2666 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
2667 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2669 // Can we convert the 'select' to CF ?
2670 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
2673 TargetLowering::SelectSupportKind SelectKind;
2675 SelectKind = TargetLowering::VectorMaskSelect;
2676 else if (SI->getType()->isVectorTy())
2677 SelectKind = TargetLowering::ScalarCondVectorVal;
2679 SelectKind = TargetLowering::ScalarValSelect;
2681 // Do we have efficient codegen support for this kind of 'selects' ?
2682 if (TLI->isSelectSupported(SelectKind)) {
2683 // We have efficient codegen support for the select instruction.
2684 // Check if it is profitable to keep this 'select'.
2685 if (!TLI->isPredictableSelectExpensive() ||
2686 !isFormingBranchFromSelectProfitable(SI))
2692 // First, we split the block containing the select into 2 blocks.
2693 BasicBlock *StartBlock = SI->getParent();
2694 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2695 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2697 // Create a new block serving as the landing pad for the branch.
2698 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2699 NextBlock->getParent(), NextBlock);
2701 // Move the unconditional branch from the block with the select in it into our
2702 // landing pad block.
2703 StartBlock->getTerminator()->eraseFromParent();
2704 BranchInst::Create(NextBlock, SmallBlock);
2706 // Insert the real conditional branch based on the original condition.
2707 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2709 // The select itself is replaced with a PHI Node.
2710 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2712 PN->addIncoming(SI->getTrueValue(), StartBlock);
2713 PN->addIncoming(SI->getFalseValue(), SmallBlock);
2714 SI->replaceAllUsesWith(PN);
2715 SI->eraseFromParent();
2717 // Instruct OptimizeBlock to skip to the next block.
2718 CurInstIterator = StartBlock->end();
2719 ++NumSelectsExpanded;
2724 bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
2725 SmallVector<int, 16> Mask(SVI->getShuffleMask());
2727 for (unsigned i = 0; i < Mask.size(); ++i) {
2728 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
2730 SplatElem = Mask[i];
2736 /// Some targets have expensive vector shifts if the lanes aren't all the same
2737 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
2738 /// it's often worth sinking a shufflevector splat down to its use so that
2739 /// codegen can spot all lanes are identical.
2740 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
2741 BasicBlock *DefBB = SVI->getParent();
2743 // Only do this xform if variable vector shifts are particularly expensive.
2744 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
2747 // We only expect better codegen by sinking a shuffle if we can recognise a
2749 if (!isBroadcastShuffle(SVI))
2752 // InsertedShuffles - Only insert a shuffle in each block once.
2753 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
2755 bool MadeChange = false;
2756 for (Value::use_iterator UI = SVI->use_begin(), E = SVI->use_end();
2758 Instruction *User = cast<Instruction>(*UI);
2760 // Figure out which BB this ext is used in.
2761 BasicBlock *UserBB = User->getParent();
2762 if (UserBB == DefBB) continue;
2764 // For now only apply this when the splat is used by a shift instruction.
2765 if (!User->isShift()) continue;
2767 // Everything checks out, sink the shuffle if the user's block doesn't
2768 // already have a copy.
2769 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
2771 if (!InsertedShuffle) {
2772 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2773 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
2775 SVI->getOperand(2), "", InsertPt);
2778 User->replaceUsesOfWith(SVI, InsertedShuffle);
2782 // If we removed all uses, nuke the shuffle.
2783 if (SVI->use_empty()) {
2784 SVI->eraseFromParent();
2791 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
2792 if (PHINode *P = dyn_cast<PHINode>(I)) {
2793 // It is possible for very late stage optimizations (such as SimplifyCFG)
2794 // to introduce PHI nodes too late to be cleaned up. If we detect such a
2795 // trivial PHI, go ahead and zap it here.
2796 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
2798 P->replaceAllUsesWith(V);
2799 P->eraseFromParent();
2806 if (CastInst *CI = dyn_cast<CastInst>(I)) {
2807 // If the source of the cast is a constant, then this should have
2808 // already been constant folded. The only reason NOT to constant fold
2809 // it is if something (e.g. LSR) was careful to place the constant
2810 // evaluation in a block other than then one that uses it (e.g. to hoist
2811 // the address of globals out of a loop). If this is the case, we don't
2812 // want to forward-subst the cast.
2813 if (isa<Constant>(CI->getOperand(0)))
2816 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2819 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
2820 bool MadeChange = MoveExtToFormExtLoad(I);
2821 return MadeChange | OptimizeExtUses(I);
2826 if (CmpInst *CI = dyn_cast<CmpInst>(I))
2827 if (!TLI || !TLI->hasMultipleConditionRegisters())
2828 return OptimizeCmpExpression(CI);
2830 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2832 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2836 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
2838 return OptimizeMemoryInst(I, SI->getOperand(1),
2839 SI->getOperand(0)->getType());
2843 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2844 if (GEPI->hasAllZeroIndices()) {
2845 /// The GEP operand must be a pointer, so must its result -> BitCast
2846 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
2847 GEPI->getName(), GEPI);
2848 GEPI->replaceAllUsesWith(NC);
2849 GEPI->eraseFromParent();
2857 if (CallInst *CI = dyn_cast<CallInst>(I))
2858 return OptimizeCallInst(CI);
2860 if (SelectInst *SI = dyn_cast<SelectInst>(I))
2861 return OptimizeSelectInst(SI);
2863 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
2864 return OptimizeShuffleVectorInst(SVI);
2869 // In this pass we look for GEP and cast instructions that are used
2870 // across basic blocks and rewrite them to improve basic-block-at-a-time
2872 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
2874 bool MadeChange = false;
2876 CurInstIterator = BB.begin();
2877 while (CurInstIterator != BB.end())
2878 MadeChange |= OptimizeInst(CurInstIterator++);
2880 MadeChange |= DupRetToEnableTailCallOpts(&BB);
2885 // llvm.dbg.value is far away from the value then iSel may not be able
2886 // handle it properly. iSel will drop llvm.dbg.value if it can not
2887 // find a node corresponding to the value.
2888 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
2889 bool MadeChange = false;
2890 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2891 Instruction *PrevNonDbgInst = NULL;
2892 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
2893 Instruction *Insn = BI; ++BI;
2894 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
2896 PrevNonDbgInst = Insn;
2900 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
2901 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
2902 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
2903 DVI->removeFromParent();
2904 if (isa<PHINode>(VI))
2905 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
2907 DVI->insertAfter(VI);