1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "codegenprepare"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
40 /// TLI - Keep a pointer of a TargetLowering to consult for determining
41 /// transformation profitability.
42 const TargetLowering *TLI;
44 static char ID; // Pass identification, replacement for typeid
45 explicit CodeGenPrepare(const TargetLowering *tli = 0)
46 : FunctionPass(&ID), TLI(tli) {}
47 bool runOnFunction(Function &F);
50 bool EliminateMostlyEmptyBlocks(Function &F);
51 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
52 void EliminateMostlyEmptyBlock(BasicBlock *BB);
53 bool OptimizeBlock(BasicBlock &BB);
54 bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
56 DenseMap<Value*,Value*> &SunkAddrs);
57 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
58 DenseMap<Value*,Value*> &SunkAddrs);
59 bool OptimizeExtUses(Instruction *I);
63 char CodeGenPrepare::ID = 0;
64 static RegisterPass<CodeGenPrepare> X("codegenprepare",
65 "Optimize for code generation");
67 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
68 return new CodeGenPrepare(TLI);
72 bool CodeGenPrepare::runOnFunction(Function &F) {
73 bool EverMadeChange = false;
75 // First pass, eliminate blocks that contain only PHI nodes and an
76 // unconditional branch.
77 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
79 bool MadeChange = true;
82 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
83 MadeChange |= OptimizeBlock(*BB);
84 EverMadeChange |= MadeChange;
86 return EverMadeChange;
89 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
90 /// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
91 /// often split edges in ways that are non-optimal for isel. Start by
92 /// eliminating these blocks so we can split them the way we want them.
93 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
94 bool MadeChange = false;
95 // Note that this intentionally skips the entry block.
96 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
99 // If this block doesn't end with an uncond branch, ignore it.
100 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
101 if (!BI || !BI->isUnconditional())
104 // If the instruction before the branch isn't a phi node, then other stuff
105 // is happening here.
106 BasicBlock::iterator BBI = BI;
107 if (BBI != BB->begin()) {
109 if (!isa<PHINode>(BBI)) continue;
112 // Do not break infinite loops.
113 BasicBlock *DestBB = BI->getSuccessor(0);
117 if (!CanMergeBlocks(BB, DestBB))
120 EliminateMostlyEmptyBlock(BB);
126 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
127 /// single uncond branch between them, and BB contains no other non-phi
129 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
130 const BasicBlock *DestBB) const {
131 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
132 // the successor. If there are more complex condition (e.g. preheaders),
133 // don't mess around with them.
134 BasicBlock::const_iterator BBI = BB->begin();
135 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
136 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
138 const Instruction *User = cast<Instruction>(*UI);
139 if (User->getParent() != DestBB || !isa<PHINode>(User))
141 // If User is inside DestBB block and it is a PHINode then check
142 // incoming value. If incoming value is not from BB then this is
143 // a complex condition (e.g. preheaders) we want to avoid here.
144 if (User->getParent() == DestBB) {
145 if (const PHINode *UPN = dyn_cast<PHINode>(User))
146 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
147 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
148 if (Insn && Insn->getParent() == BB &&
149 Insn->getParent() != UPN->getIncomingBlock(I))
156 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
157 // and DestBB may have conflicting incoming values for the block. If so, we
158 // can't merge the block.
159 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
160 if (!DestBBPN) return true; // no conflict.
162 // Collect the preds of BB.
163 SmallPtrSet<const BasicBlock*, 16> BBPreds;
164 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
165 // It is faster to get preds from a PHI than with pred_iterator.
166 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
167 BBPreds.insert(BBPN->getIncomingBlock(i));
169 BBPreds.insert(pred_begin(BB), pred_end(BB));
172 // Walk the preds of DestBB.
173 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
174 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
175 if (BBPreds.count(Pred)) { // Common predecessor?
176 BBI = DestBB->begin();
177 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
178 const Value *V1 = PN->getIncomingValueForBlock(Pred);
179 const Value *V2 = PN->getIncomingValueForBlock(BB);
181 // If V2 is a phi node in BB, look up what the mapped value will be.
182 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
183 if (V2PN->getParent() == BB)
184 V2 = V2PN->getIncomingValueForBlock(Pred);
186 // If there is a conflict, bail out.
187 if (V1 != V2) return false;
196 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
197 /// an unconditional branch in it.
198 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
199 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
200 BasicBlock *DestBB = BI->getSuccessor(0);
202 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
204 // If the destination block has a single pred, then this is a trivial edge,
206 if (DestBB->getSinglePredecessor()) {
207 // If DestBB has single-entry PHI nodes, fold them.
208 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
209 Value *NewVal = PN->getIncomingValue(0);
210 // Replace self referencing PHI with undef, it must be dead.
211 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
212 PN->replaceAllUsesWith(NewVal);
213 PN->eraseFromParent();
216 // Splice all the PHI nodes from BB over to DestBB.
217 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
220 // Anything that branched to BB now branches to DestBB.
221 BB->replaceAllUsesWith(DestBB);
224 BB->eraseFromParent();
226 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
230 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
231 // to handle the new incoming edges it is about to have.
233 for (BasicBlock::iterator BBI = DestBB->begin();
234 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
235 // Remove the incoming value for BB, and remember it.
236 Value *InVal = PN->removeIncomingValue(BB, false);
238 // Two options: either the InVal is a phi node defined in BB or it is some
239 // value that dominates BB.
240 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
241 if (InValPhi && InValPhi->getParent() == BB) {
242 // Add all of the input values of the input PHI as inputs of this phi.
243 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
244 PN->addIncoming(InValPhi->getIncomingValue(i),
245 InValPhi->getIncomingBlock(i));
247 // Otherwise, add one instance of the dominating value for each edge that
248 // we will be adding.
249 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
250 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
251 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
253 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
254 PN->addIncoming(InVal, *PI);
259 // The PHIs are now updated, change everything that refers to BB to use
260 // DestBB and remove BB.
261 BB->replaceAllUsesWith(DestBB);
262 BB->eraseFromParent();
264 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
268 /// SplitEdgeNicely - Split the critical edge from TI to its specified
269 /// successor if it will improve codegen. We only do this if the successor has
270 /// phi nodes (otherwise critical edges are ok). If there is already another
271 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
272 /// instead of introducing a new block.
273 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
274 BasicBlock *TIBB = TI->getParent();
275 BasicBlock *Dest = TI->getSuccessor(SuccNum);
276 assert(isa<PHINode>(Dest->begin()) &&
277 "This should only be called if Dest has a PHI!");
279 // As a hack, never split backedges of loops. Even though the copy for any
280 // PHIs inserted on the backedge would be dead for exits from the loop, we
281 // assume that the cost of *splitting* the backedge would be too high.
285 /// TIPHIValues - This array is lazily computed to determine the values of
286 /// PHIs in Dest that TI would provide.
287 SmallVector<Value*, 32> TIPHIValues;
289 // Check to see if Dest has any blocks that can be used as a split edge for
291 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
292 BasicBlock *Pred = *PI;
293 // To be usable, the pred has to end with an uncond branch to the dest.
294 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
295 if (!PredBr || !PredBr->isUnconditional() ||
296 // Must be empty other than the branch.
297 &Pred->front() != PredBr ||
298 // Cannot be the entry block; its label does not get emitted.
299 Pred == &(Dest->getParent()->getEntryBlock()))
302 // Finally, since we know that Dest has phi nodes in it, we have to make
303 // sure that jumping to Pred will have the same affect as going to Dest in
304 // terms of PHI values.
307 bool FoundMatch = true;
308 for (BasicBlock::iterator I = Dest->begin();
309 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
310 if (PHINo == TIPHIValues.size())
311 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
313 // If the PHI entry doesn't work, we can't use this pred.
314 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
320 // If we found a workable predecessor, change TI to branch to Succ.
322 Dest->removePredecessor(TIBB);
323 TI->setSuccessor(SuccNum, Pred);
328 SplitCriticalEdge(TI, SuccNum, P, true);
331 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
332 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
333 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
334 /// registers that must be created and coalesced.
336 /// Return true if any changes are made.
337 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
338 // If this is a noop copy,
339 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
340 MVT DstVT = TLI.getValueType(CI->getType());
342 // This is an fp<->int conversion?
343 if (SrcVT.isInteger() != DstVT.isInteger())
346 // If this is an extension, it will be a zero or sign extension, which
348 if (SrcVT.bitsLT(DstVT)) return false;
350 // If these values will be promoted, find out what they will be promoted
351 // to. This helps us consider truncates on PPC as noop copies when they
353 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
354 SrcVT = TLI.getTypeToTransformTo(SrcVT);
355 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
356 DstVT = TLI.getTypeToTransformTo(DstVT);
358 // If, after promotion, these are the same types, this is a noop copy.
362 BasicBlock *DefBB = CI->getParent();
364 /// InsertedCasts - Only insert a cast in each block once.
365 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
367 bool MadeChange = false;
368 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
370 Use &TheUse = UI.getUse();
371 Instruction *User = cast<Instruction>(*UI);
373 // Figure out which BB this cast is used in. For PHI's this is the
374 // appropriate predecessor block.
375 BasicBlock *UserBB = User->getParent();
376 if (PHINode *PN = dyn_cast<PHINode>(User)) {
377 unsigned OpVal = UI.getOperandNo()/2;
378 UserBB = PN->getIncomingBlock(OpVal);
381 // Preincrement use iterator so we don't invalidate it.
384 // If this user is in the same block as the cast, don't change the cast.
385 if (UserBB == DefBB) continue;
387 // If we have already inserted a cast into this block, use it.
388 CastInst *&InsertedCast = InsertedCasts[UserBB];
391 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
394 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
399 // Replace a use of the cast with a use of the new cast.
400 TheUse = InsertedCast;
403 // If we removed all uses, nuke the cast.
404 if (CI->use_empty()) {
405 CI->eraseFromParent();
412 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
413 /// the number of virtual registers that must be created and coalesced. This is
414 /// a clear win except on targets with multiple condition code registers
415 /// (PowerPC), where it might lose; some adjustment may be wanted there.
417 /// Return true if any changes are made.
418 static bool OptimizeCmpExpression(CmpInst *CI){
420 BasicBlock *DefBB = CI->getParent();
422 /// InsertedCmp - Only insert a cmp in each block once.
423 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
425 bool MadeChange = false;
426 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
428 Use &TheUse = UI.getUse();
429 Instruction *User = cast<Instruction>(*UI);
431 // Preincrement use iterator so we don't invalidate it.
434 // Don't bother for PHI nodes.
435 if (isa<PHINode>(User))
438 // Figure out which BB this cmp is used in.
439 BasicBlock *UserBB = User->getParent();
441 // If this user is in the same block as the cmp, don't change the cmp.
442 if (UserBB == DefBB) continue;
444 // If we have already inserted a cmp into this block, use it.
445 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
448 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
451 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
452 CI->getOperand(1), "", InsertPt);
456 // Replace a use of the cmp with a use of the new cmp.
457 TheUse = InsertedCmp;
460 // If we removed all uses, nuke the cmp.
462 CI->eraseFromParent();
467 /// EraseDeadInstructions - Erase any dead instructions
468 static void EraseDeadInstructions(Value *V) {
469 Instruction *I = dyn_cast<Instruction>(V);
470 if (!I || !I->use_empty()) return;
472 SmallPtrSet<Instruction*, 16> Insts;
475 while (!Insts.empty()) {
478 if (isInstructionTriviallyDead(I)) {
479 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
480 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
482 I->eraseFromParent();
488 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
489 /// which holds actual Value*'s for register values.
490 struct ExtAddrMode : public TargetLowering::AddrMode {
493 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
494 void print(OStream &OS) const;
500 } // end anonymous namespace
502 static OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
508 void ExtAddrMode::print(OStream &OS) const {
509 bool NeedPlus = false;
512 OS << (NeedPlus ? " + " : "")
513 << "GV:%" << BaseGV->getName(), NeedPlus = true;
516 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
519 OS << (NeedPlus ? " + " : "")
520 << "Base:%" << BaseReg->getName(), NeedPlus = true;
522 OS << (NeedPlus ? " + " : "")
523 << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
528 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
529 const Type *AccessTy, ExtAddrMode &AddrMode,
530 SmallVector<Instruction*, 16> &AddrModeInsts,
531 const TargetLowering &TLI, unsigned Depth);
533 /// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
534 /// Addr into the specified addressing mode. If Addr can't be added to AddrMode
535 /// this returns false. This assumes that Addr is either a pointer type or
536 /// intptr_t for the target.
537 static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
538 ExtAddrMode &AddrMode,
539 SmallVector<Instruction*, 16> &AddrModeInsts,
540 const TargetLowering &TLI,
543 // If this is a global variable, fold it into the addressing mode if possible.
544 if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
545 if (AddrMode.BaseGV == 0) {
546 AddrMode.BaseGV = GV;
547 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
551 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
552 AddrMode.BaseOffs += CI->getSExtValue();
553 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
555 AddrMode.BaseOffs -= CI->getSExtValue();
556 } else if (isa<ConstantPointerNull>(Addr)) {
560 // Look through constant exprs and instructions.
561 unsigned Opcode = ~0U;
563 if (Instruction *I = dyn_cast<Instruction>(Addr)) {
564 Opcode = I->getOpcode();
566 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
567 Opcode = CE->getOpcode();
571 // Limit recursion to avoid exponential behavior.
572 if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
574 // If this is really an instruction, add it to our list of related
576 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
577 AddrModeInsts.push_back(I);
580 if (AddrInst && !AddrInst->hasOneUse())
585 case Instruction::PtrToInt:
586 // PtrToInt is always a noop, as we know that the int type is pointer sized.
587 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
588 AddrMode, AddrModeInsts, TLI, Depth))
591 case Instruction::IntToPtr:
592 // This inttoptr is a no-op if the integer type is pointer sized.
593 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
594 TLI.getPointerTy()) {
595 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
596 AddrMode, AddrModeInsts, TLI, Depth))
600 case Instruction::Add: {
601 // Check to see if we can merge in the RHS then the LHS. If so, we win.
602 ExtAddrMode BackupAddrMode = AddrMode;
603 unsigned OldSize = AddrModeInsts.size();
604 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
605 AddrMode, AddrModeInsts, TLI, Depth+1) &&
606 FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
607 AddrMode, AddrModeInsts, TLI, Depth+1))
610 // Restore the old addr mode info.
611 AddrMode = BackupAddrMode;
612 AddrModeInsts.resize(OldSize);
614 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
615 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
616 AddrMode, AddrModeInsts, TLI, Depth+1) &&
617 FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
618 AddrMode, AddrModeInsts, TLI, Depth+1))
621 // Otherwise we definitely can't merge the ADD in.
622 AddrMode = BackupAddrMode;
623 AddrModeInsts.resize(OldSize);
626 case Instruction::Or: {
627 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
629 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
632 case Instruction::Mul:
633 case Instruction::Shl: {
634 // Can only handle X*C and X << C, and can only handle this when the scale
635 // field is available.
636 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
638 int64_t Scale = RHS->getSExtValue();
639 if (Opcode == Instruction::Shl)
642 if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
643 AddrMode, AddrModeInsts, TLI, Depth))
647 case Instruction::GetElementPtr: {
648 // Scan the GEP. We check it if it contains constant offsets and at most
649 // one variable offset.
650 int VariableOperand = -1;
651 unsigned VariableScale = 0;
653 int64_t ConstantOffset = 0;
654 const TargetData *TD = TLI.getTargetData();
655 gep_type_iterator GTI = gep_type_begin(AddrInst);
656 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
657 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
658 const StructLayout *SL = TD->getStructLayout(STy);
660 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
661 ConstantOffset += SL->getElementOffset(Idx);
663 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
664 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
665 ConstantOffset += CI->getSExtValue()*TypeSize;
666 } else if (TypeSize) { // Scales of zero don't do anything.
667 // We only allow one variable index at the moment.
668 if (VariableOperand != -1) {
669 VariableOperand = -2;
673 // Remember the variable index.
675 VariableScale = TypeSize;
680 // If the GEP had multiple variable indices, punt.
681 if (VariableOperand == -2)
684 // A common case is for the GEP to only do a constant offset. In this case,
685 // just add it to the disp field and check validity.
686 if (VariableOperand == -1) {
687 AddrMode.BaseOffs += ConstantOffset;
688 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
689 // Check to see if we can fold the base pointer in too.
690 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
691 AddrMode, AddrModeInsts, TLI,
695 AddrMode.BaseOffs -= ConstantOffset;
697 // Check that this has no base reg yet. If so, we won't have a place to
698 // put the base of the GEP (assuming it is not a null ptr).
699 bool SetBaseReg = false;
700 if (AddrMode.HasBaseReg) {
701 if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
704 AddrMode.HasBaseReg = true;
705 AddrMode.BaseReg = AddrInst->getOperand(0);
709 // See if the scale amount is valid for this target.
710 AddrMode.BaseOffs += ConstantOffset;
711 if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
712 VariableScale, AccessTy, AddrMode,
713 AddrModeInsts, TLI, Depth)) {
714 if (!SetBaseReg) return true;
716 // If this match succeeded, we know that we can form an address with the
717 // GepBase as the basereg. See if we can match *more*.
718 AddrMode.HasBaseReg = false;
719 AddrMode.BaseReg = 0;
720 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
721 AddrMode, AddrModeInsts, TLI,
724 // Strange, shouldn't happen. Restore the base reg and succeed the easy
726 AddrMode.HasBaseReg = true;
727 AddrMode.BaseReg = AddrInst->getOperand(0);
731 AddrMode.BaseOffs -= ConstantOffset;
733 AddrMode.HasBaseReg = false;
734 AddrMode.BaseReg = 0;
741 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
742 assert(AddrModeInsts.back() == I && "Stack imbalance"); I = I;
743 AddrModeInsts.pop_back();
746 // Worse case, the target should support [reg] addressing modes. :)
747 if (!AddrMode.HasBaseReg) {
748 AddrMode.HasBaseReg = true;
749 // Still check for legality in case the target supports [imm] but not [i+r].
750 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
751 AddrMode.BaseReg = Addr;
754 AddrMode.HasBaseReg = false;
757 // If the base register is already taken, see if we can do [r+r].
758 if (AddrMode.Scale == 0) {
760 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
761 AddrMode.ScaledReg = Addr;
770 /// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
771 /// addressing mode. Return true if this addr mode is legal for the target,
773 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
774 const Type *AccessTy, ExtAddrMode &AddrMode,
775 SmallVector<Instruction*, 16> &AddrModeInsts,
776 const TargetLowering &TLI, unsigned Depth) {
777 // If we already have a scale of this value, we can add to it, otherwise, we
778 // need an available scale field.
779 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
782 ExtAddrMode InputAddrMode = AddrMode;
784 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
785 // [A+B + A*7] -> [B+A*8].
786 AddrMode.Scale += Scale;
787 AddrMode.ScaledReg = ScaleReg;
789 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
790 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
791 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
792 // X*Scale + C*Scale to addr mode.
793 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
794 if (BinOp && BinOp->getOpcode() == Instruction::Add &&
795 isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
797 InputAddrMode.Scale = Scale;
798 InputAddrMode.ScaledReg = BinOp->getOperand(0);
799 InputAddrMode.BaseOffs +=
800 cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
801 if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
802 AddrModeInsts.push_back(BinOp);
803 AddrMode = InputAddrMode;
808 // Otherwise, not (x+c)*scale, just return what we have.
812 // Otherwise, back this attempt out.
813 AddrMode.Scale -= Scale;
814 if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
820 /// IsNonLocalValue - Return true if the specified values are defined in a
821 /// different basic block than BB.
822 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
823 if (Instruction *I = dyn_cast<Instruction>(V))
824 return I->getParent() != BB;
828 /// OptimizeLoadStoreInst - Load and Store Instructions have often have
829 /// addressing modes that can do significant amounts of computation. As such,
830 /// instruction selection will try to get the load or store to do as much
831 /// computation as possible for the program. The problem is that isel can only
832 /// see within a single block. As such, we sink as much legal addressing mode
833 /// stuff into the block as possible.
834 bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
835 const Type *AccessTy,
836 DenseMap<Value*,Value*> &SunkAddrs) {
837 // Figure out what addressing mode will be built up for this operation.
838 SmallVector<Instruction*, 16> AddrModeInsts;
839 ExtAddrMode AddrMode;
840 bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
841 AddrModeInsts, *TLI, 0);
842 Success = Success; assert(Success && "Couldn't select *anything*?");
844 // Check to see if any of the instructions supersumed by this addr mode are
845 // non-local to I's BB.
846 bool AnyNonLocal = false;
847 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
848 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
854 // If all the instructions matched are already in this BB, don't do anything.
856 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
860 // Insert this computation right after this user. Since our caller is
861 // scanning from the top of the BB to the bottom, reuse of the expr are
862 // guaranteed to happen later.
863 BasicBlock::iterator InsertPt = LdStInst;
865 // Now that we determined the addressing expression we want to use and know
866 // that we have to sink it into this block. Check to see if we have already
867 // done this for some other load/store instr in this block. If so, reuse the
869 Value *&SunkAddr = SunkAddrs[Addr];
871 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
872 if (SunkAddr->getType() != Addr->getType())
873 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
875 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
876 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
879 // Start with the scale value.
880 if (AddrMode.Scale) {
881 Value *V = AddrMode.ScaledReg;
882 if (V->getType() == IntPtrTy) {
884 } else if (isa<PointerType>(V->getType())) {
885 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
886 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
887 cast<IntegerType>(V->getType())->getBitWidth()) {
888 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
890 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
892 if (AddrMode.Scale != 1)
893 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
895 "sunkaddr", InsertPt);
899 // Add in the base register.
900 if (AddrMode.BaseReg) {
901 Value *V = AddrMode.BaseReg;
902 if (V->getType() != IntPtrTy)
903 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
905 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
910 // Add in the BaseGV if present.
911 if (AddrMode.BaseGV) {
912 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
915 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
920 // Add in the Base Offset if present.
921 if (AddrMode.BaseOffs) {
922 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
924 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
930 SunkAddr = Constant::getNullValue(Addr->getType());
932 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
935 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
937 if (Addr->use_empty())
938 EraseDeadInstructions(Addr);
942 /// OptimizeInlineAsmInst - If there are any memory operands, use
943 /// OptimizeLoadStoreInt to sink their address computing into the block when
944 /// possible / profitable.
945 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
946 DenseMap<Value*,Value*> &SunkAddrs) {
947 bool MadeChange = false;
948 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
950 // Do a prepass over the constraints, canonicalizing them, and building up the
951 // ConstraintOperands list.
952 std::vector<InlineAsm::ConstraintInfo>
953 ConstraintInfos = IA->ParseConstraints();
955 /// ConstraintOperands - Information about all of the constraints.
956 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
957 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
958 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
960 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
961 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
963 // Compute the value type for each operand.
964 switch (OpInfo.Type) {
965 case InlineAsm::isOutput:
966 if (OpInfo.isIndirect)
967 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
969 case InlineAsm::isInput:
970 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
972 case InlineAsm::isClobber:
977 // Compute the constraint code and ConstraintType to use.
978 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
979 OpInfo.ConstraintType == TargetLowering::C_Memory);
981 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
983 Value *OpVal = OpInfo.CallOperandVal;
984 MadeChange |= OptimizeLoadStoreInst(I, OpVal, OpVal->getType(),
992 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
993 BasicBlock *DefBB = I->getParent();
995 // If both result of the {s|z}xt and its source are live out, rewrite all
996 // other uses of the source with result of extension.
997 Value *Src = I->getOperand(0);
998 if (Src->hasOneUse())
1001 // Only do this xform if truncating is free.
1002 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1005 // Only safe to perform the optimization if the source is also defined in
1007 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1010 bool DefIsLiveOut = false;
1011 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1013 Instruction *User = cast<Instruction>(*UI);
1015 // Figure out which BB this ext is used in.
1016 BasicBlock *UserBB = User->getParent();
1017 if (UserBB == DefBB) continue;
1018 DefIsLiveOut = true;
1024 // Make sure non of the uses are PHI nodes.
1025 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1027 Instruction *User = cast<Instruction>(*UI);
1028 BasicBlock *UserBB = User->getParent();
1029 if (UserBB == DefBB) continue;
1030 // Be conservative. We don't want this xform to end up introducing
1031 // reloads just before load / store instructions.
1032 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1036 // InsertedTruncs - Only insert one trunc in each block once.
1037 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1039 bool MadeChange = false;
1040 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1042 Use &TheUse = UI.getUse();
1043 Instruction *User = cast<Instruction>(*UI);
1045 // Figure out which BB this ext is used in.
1046 BasicBlock *UserBB = User->getParent();
1047 if (UserBB == DefBB) continue;
1049 // Both src and def are live in this block. Rewrite the use.
1050 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1052 if (!InsertedTrunc) {
1053 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
1055 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1058 // Replace a use of the {s|z}ext source with a use of the result.
1059 TheUse = InsertedTrunc;
1067 // In this pass we look for GEP and cast instructions that are used
1068 // across basic blocks and rewrite them to improve basic-block-at-a-time
1070 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1071 bool MadeChange = false;
1073 // Split all critical edges where the dest block has a PHI and where the phi
1074 // has shared immediate operands.
1075 TerminatorInst *BBTI = BB.getTerminator();
1076 if (BBTI->getNumSuccessors() > 1) {
1077 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1078 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1079 isCriticalEdge(BBTI, i, true))
1080 SplitEdgeNicely(BBTI, i, this);
1084 // Keep track of non-local addresses that have been sunk into this block.
1085 // This allows us to avoid inserting duplicate code for blocks with multiple
1086 // load/stores of the same address.
1087 DenseMap<Value*, Value*> SunkAddrs;
1089 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1090 Instruction *I = BBI++;
1092 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1093 // If the source of the cast is a constant, then this should have
1094 // already been constant folded. The only reason NOT to constant fold
1095 // it is if something (e.g. LSR) was careful to place the constant
1096 // evaluation in a block other than then one that uses it (e.g. to hoist
1097 // the address of globals out of a loop). If this is the case, we don't
1098 // want to forward-subst the cast.
1099 if (isa<Constant>(CI->getOperand(0)))
1102 bool Change = false;
1104 Change = OptimizeNoopCopyExpression(CI, *TLI);
1105 MadeChange |= Change;
1108 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1109 MadeChange |= OptimizeExtUses(I);
1110 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1111 MadeChange |= OptimizeCmpExpression(CI);
1112 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1114 MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
1116 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1118 MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
1119 SI->getOperand(0)->getType(),
1121 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1122 if (GEPI->hasAllZeroIndices()) {
1123 /// The GEP operand must be a pointer, so must its result -> BitCast
1124 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1125 GEPI->getName(), GEPI);
1126 GEPI->replaceAllUsesWith(NC);
1127 GEPI->eraseFromParent();
1131 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1132 // If we found an inline asm expession, and if the target knows how to
1133 // lower it to normal LLVM code, do so now.
1134 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1135 if (const TargetAsmInfo *TAI =
1136 TLI->getTargetMachine().getTargetAsmInfo()) {
1137 if (TAI->ExpandInlineAsm(CI))
1140 // Sink address computing for memory operands into the block.
1141 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);