CodeGenPrep: wrangle IR to exploit AArch64 tbz/tbnz inst.
[oota-llvm.git] / lib / CodeGen / CodeGenPrepare.cpp
1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
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/Analysis/InstructionSimplify.h"
22 #include "llvm/IR/CallSite.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/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/IR/ValueMap.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.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"
46 using namespace llvm;
47 using namespace llvm::PatternMatch;
48
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 "
53                       "sunken Cmps");
54 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
55                        "of sunken Casts");
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");
63 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
64
65 static cl::opt<bool> DisableBranchOpts(
66   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67   cl::desc("Disable branch optimizations in CodeGenPrepare"));
68
69 static cl::opt<bool> DisableSelectToBranch(
70   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
71   cl::desc("Disable select to branch conversion."));
72
73 static cl::opt<bool> EnableAndCmpSinking(
74    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
75    cl::desc("Enable sinkinig and/cmp into branches."));
76
77 namespace {
78 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
79 typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
80
81   class CodeGenPrepare : public FunctionPass {
82     /// TLI - Keep a pointer of a TargetLowering to consult for determining
83     /// transformation profitability.
84     const TargetMachine *TM;
85     const TargetLowering *TLI;
86     const TargetLibraryInfo *TLInfo;
87     DominatorTree *DT;
88
89     /// CurInstIterator - As we scan instructions optimizing them, this is the
90     /// next instruction to optimize.  Xforms that can invalidate this should
91     /// update it.
92     BasicBlock::iterator CurInstIterator;
93
94     /// Keeps track of non-local addresses that have been sunk into a block.
95     /// This allows us to avoid inserting duplicate code for blocks with
96     /// multiple load/stores of the same address.
97     ValueMap<Value*, Value*> SunkAddrs;
98
99     /// Keeps track of all truncates inserted for the current function.
100     SetOfInstrs InsertedTruncsSet;
101     /// Keeps track of the type of the related instruction before their
102     /// promotion for the current function.
103     InstrToOrigTy PromotedInsts;
104
105     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
106     /// be updated.
107     bool ModifiedDT;
108
109     /// OptSize - True if optimizing for size.
110     bool OptSize;
111
112   public:
113     static char ID; // Pass identification, replacement for typeid
114     explicit CodeGenPrepare(const TargetMachine *TM = 0)
115       : FunctionPass(ID), TM(TM), TLI(0) {
116         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
117       }
118     bool runOnFunction(Function &F) override;
119
120     const char *getPassName() const override { return "CodeGen Prepare"; }
121
122     void getAnalysisUsage(AnalysisUsage &AU) const override {
123       AU.addPreserved<DominatorTreeWrapperPass>();
124       AU.addRequired<TargetLibraryInfo>();
125     }
126
127   private:
128     bool EliminateFallThrough(Function &F);
129     bool EliminateMostlyEmptyBlocks(Function &F);
130     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
131     void EliminateMostlyEmptyBlock(BasicBlock *BB);
132     bool OptimizeBlock(BasicBlock &BB);
133     bool OptimizeInst(Instruction *I);
134     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
135     bool OptimizeInlineAsmInst(CallInst *CS);
136     bool OptimizeCallInst(CallInst *CI);
137     bool MoveExtToFormExtLoad(Instruction *I);
138     bool OptimizeExtUses(Instruction *I);
139     bool OptimizeSelectInst(SelectInst *SI);
140     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
141     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
142     bool PlaceDbgValues(Function &F);
143     bool sinkAndCmp(Function &F);
144   };
145 }
146
147 char CodeGenPrepare::ID = 0;
148 static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
149   initializeTargetLibraryInfoPass(Registry);
150   PassInfo *PI = new PassInfo(
151       "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
152       PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
153       PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
154   Registry.registerPass(*PI, true);
155   return PI;
156 }
157
158 void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
159   CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
160 }
161
162 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
163   return new CodeGenPrepare(TM);
164 }
165
166 bool CodeGenPrepare::runOnFunction(Function &F) {
167   bool EverMadeChange = false;
168   // Clear per function information.
169   InsertedTruncsSet.clear();
170   PromotedInsts.clear();
171
172   ModifiedDT = false;
173   if (TM) TLI = TM->getTargetLowering();
174   TLInfo = &getAnalysis<TargetLibraryInfo>();
175   DominatorTreeWrapperPass *DTWP =
176       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
177   DT = DTWP ? &DTWP->getDomTree() : 0;
178   OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
179                                            Attribute::OptimizeForSize);
180
181   /// This optimization identifies DIV instructions that can be
182   /// profitably bypassed and carried out with a shorter, faster divide.
183   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
184     const DenseMap<unsigned int, unsigned int> &BypassWidths =
185        TLI->getBypassSlowDivWidths();
186     for (Function::iterator I = F.begin(); I != F.end(); I++)
187       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
188   }
189
190   // Eliminate blocks that contain only PHI nodes and an
191   // unconditional branch.
192   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
193
194   // llvm.dbg.value is far away from the value then iSel may not be able
195   // handle it properly. iSel will drop llvm.dbg.value if it can not
196   // find a node corresponding to the value.
197   EverMadeChange |= PlaceDbgValues(F);
198
199   // If there is a mask, compare against zero, and branch that can be combined
200   // into a single target instruction, push the mask and compare into branch
201   // users. Do this before OptimizeBlock -> OptimizeInst ->
202   // OptimizeCmpExpression, which perturbs the pattern being searched for.
203   if (!DisableBranchOpts)
204     EverMadeChange |= sinkAndCmp(F);
205
206   bool MadeChange = true;
207   while (MadeChange) {
208     MadeChange = false;
209     for (Function::iterator I = F.begin(); I != F.end(); ) {
210       BasicBlock *BB = I++;
211       MadeChange |= OptimizeBlock(*BB);
212     }
213     EverMadeChange |= MadeChange;
214   }
215
216   SunkAddrs.clear();
217
218   if (!DisableBranchOpts) {
219     MadeChange = false;
220     SmallPtrSet<BasicBlock*, 8> WorkList;
221     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
222       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
223       MadeChange |= ConstantFoldTerminator(BB, true);
224       if (!MadeChange) continue;
225
226       for (SmallVectorImpl<BasicBlock*>::iterator
227              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
228         if (pred_begin(*II) == pred_end(*II))
229           WorkList.insert(*II);
230     }
231
232     // Delete the dead blocks and any of their dead successors.
233     MadeChange |= !WorkList.empty();
234     while (!WorkList.empty()) {
235       BasicBlock *BB = *WorkList.begin();
236       WorkList.erase(BB);
237       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
238
239       DeleteDeadBlock(BB);
240
241       for (SmallVectorImpl<BasicBlock*>::iterator
242              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
243         if (pred_begin(*II) == pred_end(*II))
244           WorkList.insert(*II);
245     }
246
247     // Merge pairs of basic blocks with unconditional branches, connected by
248     // a single edge.
249     if (EverMadeChange || MadeChange)
250       MadeChange |= EliminateFallThrough(F);
251
252     if (MadeChange)
253       ModifiedDT = true;
254     EverMadeChange |= MadeChange;
255   }
256
257   if (ModifiedDT && DT)
258     DT->recalculate(F);
259
260   return EverMadeChange;
261 }
262
263 /// EliminateFallThrough - Merge basic blocks which are connected
264 /// by a single edge, where one of the basic blocks has a single successor
265 /// pointing to the other basic block, which has a single predecessor.
266 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
267   bool Changed = false;
268   // Scan all of the blocks in the function, except for the entry block.
269   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
270     BasicBlock *BB = I++;
271     // If the destination block has a single pred, then this is a trivial
272     // edge, just collapse it.
273     BasicBlock *SinglePred = BB->getSinglePredecessor();
274
275     // Don't merge if BB's address is taken.
276     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
277
278     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
279     if (Term && !Term->isConditional()) {
280       Changed = true;
281       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
282       // Remember if SinglePred was the entry block of the function.
283       // If so, we will need to move BB back to the entry position.
284       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
285       MergeBasicBlockIntoOnlyPred(BB, this);
286
287       if (isEntry && BB != &BB->getParent()->getEntryBlock())
288         BB->moveBefore(&BB->getParent()->getEntryBlock());
289
290       // We have erased a block. Update the iterator.
291       I = BB;
292     }
293   }
294   return Changed;
295 }
296
297 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
298 /// debug info directives, and an unconditional branch.  Passes before isel
299 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
300 /// isel.  Start by eliminating these blocks so we can split them the way we
301 /// want them.
302 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
303   bool MadeChange = false;
304   // Note that this intentionally skips the entry block.
305   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
306     BasicBlock *BB = I++;
307
308     // If this block doesn't end with an uncond branch, ignore it.
309     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
310     if (!BI || !BI->isUnconditional())
311       continue;
312
313     // If the instruction before the branch (skipping debug info) isn't a phi
314     // node, then other stuff is happening here.
315     BasicBlock::iterator BBI = BI;
316     if (BBI != BB->begin()) {
317       --BBI;
318       while (isa<DbgInfoIntrinsic>(BBI)) {
319         if (BBI == BB->begin())
320           break;
321         --BBI;
322       }
323       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
324         continue;
325     }
326
327     // Do not break infinite loops.
328     BasicBlock *DestBB = BI->getSuccessor(0);
329     if (DestBB == BB)
330       continue;
331
332     if (!CanMergeBlocks(BB, DestBB))
333       continue;
334
335     EliminateMostlyEmptyBlock(BB);
336     MadeChange = true;
337   }
338   return MadeChange;
339 }
340
341 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
342 /// single uncond branch between them, and BB contains no other non-phi
343 /// instructions.
344 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
345                                     const BasicBlock *DestBB) const {
346   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
347   // the successor.  If there are more complex condition (e.g. preheaders),
348   // don't mess around with them.
349   BasicBlock::const_iterator BBI = BB->begin();
350   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
351     for (const User *U : PN->users()) {
352       const Instruction *UI = cast<Instruction>(U);
353       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
354         return false;
355       // If User is inside DestBB block and it is a PHINode then check
356       // incoming value. If incoming value is not from BB then this is
357       // a complex condition (e.g. preheaders) we want to avoid here.
358       if (UI->getParent() == DestBB) {
359         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
360           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
361             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
362             if (Insn && Insn->getParent() == BB &&
363                 Insn->getParent() != UPN->getIncomingBlock(I))
364               return false;
365           }
366       }
367     }
368   }
369
370   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
371   // and DestBB may have conflicting incoming values for the block.  If so, we
372   // can't merge the block.
373   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
374   if (!DestBBPN) return true;  // no conflict.
375
376   // Collect the preds of BB.
377   SmallPtrSet<const BasicBlock*, 16> BBPreds;
378   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
379     // It is faster to get preds from a PHI than with pred_iterator.
380     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
381       BBPreds.insert(BBPN->getIncomingBlock(i));
382   } else {
383     BBPreds.insert(pred_begin(BB), pred_end(BB));
384   }
385
386   // Walk the preds of DestBB.
387   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
388     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
389     if (BBPreds.count(Pred)) {   // Common predecessor?
390       BBI = DestBB->begin();
391       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
392         const Value *V1 = PN->getIncomingValueForBlock(Pred);
393         const Value *V2 = PN->getIncomingValueForBlock(BB);
394
395         // If V2 is a phi node in BB, look up what the mapped value will be.
396         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
397           if (V2PN->getParent() == BB)
398             V2 = V2PN->getIncomingValueForBlock(Pred);
399
400         // If there is a conflict, bail out.
401         if (V1 != V2) return false;
402       }
403     }
404   }
405
406   return true;
407 }
408
409
410 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
411 /// an unconditional branch in it.
412 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
413   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
414   BasicBlock *DestBB = BI->getSuccessor(0);
415
416   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
417
418   // If the destination block has a single pred, then this is a trivial edge,
419   // just collapse it.
420   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
421     if (SinglePred != DestBB) {
422       // Remember if SinglePred was the entry block of the function.  If so, we
423       // will need to move BB back to the entry position.
424       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
425       MergeBasicBlockIntoOnlyPred(DestBB, this);
426
427       if (isEntry && BB != &BB->getParent()->getEntryBlock())
428         BB->moveBefore(&BB->getParent()->getEntryBlock());
429
430       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
431       return;
432     }
433   }
434
435   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
436   // to handle the new incoming edges it is about to have.
437   PHINode *PN;
438   for (BasicBlock::iterator BBI = DestBB->begin();
439        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
440     // Remove the incoming value for BB, and remember it.
441     Value *InVal = PN->removeIncomingValue(BB, false);
442
443     // Two options: either the InVal is a phi node defined in BB or it is some
444     // value that dominates BB.
445     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
446     if (InValPhi && InValPhi->getParent() == BB) {
447       // Add all of the input values of the input PHI as inputs of this phi.
448       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
449         PN->addIncoming(InValPhi->getIncomingValue(i),
450                         InValPhi->getIncomingBlock(i));
451     } else {
452       // Otherwise, add one instance of the dominating value for each edge that
453       // we will be adding.
454       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
455         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
456           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
457       } else {
458         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
459           PN->addIncoming(InVal, *PI);
460       }
461     }
462   }
463
464   // The PHIs are now updated, change everything that refers to BB to use
465   // DestBB and remove BB.
466   BB->replaceAllUsesWith(DestBB);
467   if (DT && !ModifiedDT) {
468     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
469     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
470     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
471     DT->changeImmediateDominator(DestBB, NewIDom);
472     DT->eraseNode(BB);
473   }
474   BB->eraseFromParent();
475   ++NumBlocksElim;
476
477   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
478 }
479
480 /// SinkCast - Sink the specified cast instruction into its user blocks
481 static bool SinkCast(CastInst *CI) {
482   BasicBlock *DefBB = CI->getParent();
483
484   /// InsertedCasts - Only insert a cast in each block once.
485   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
486
487   bool MadeChange = false;
488   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
489        UI != E; ) {
490     Use &TheUse = UI.getUse();
491     Instruction *User = cast<Instruction>(*UI);
492
493     // Figure out which BB this cast is used in.  For PHI's this is the
494     // appropriate predecessor block.
495     BasicBlock *UserBB = User->getParent();
496     if (PHINode *PN = dyn_cast<PHINode>(User)) {
497       UserBB = PN->getIncomingBlock(TheUse);
498     }
499
500     // Preincrement use iterator so we don't invalidate it.
501     ++UI;
502
503     // If this user is in the same block as the cast, don't change the cast.
504     if (UserBB == DefBB) continue;
505
506     // If we have already inserted a cast into this block, use it.
507     CastInst *&InsertedCast = InsertedCasts[UserBB];
508
509     if (!InsertedCast) {
510       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
511       InsertedCast =
512         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
513                          InsertPt);
514       MadeChange = true;
515     }
516
517     // Replace a use of the cast with a use of the new cast.
518     TheUse = InsertedCast;
519     ++NumCastUses;
520   }
521
522   // If we removed all uses, nuke the cast.
523   if (CI->use_empty()) {
524     CI->eraseFromParent();
525     MadeChange = true;
526   }
527
528   return MadeChange;
529 }
530
531 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
532 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
533 /// sink it into user blocks to reduce the number of virtual
534 /// registers that must be created and coalesced.
535 ///
536 /// Return true if any changes are made.
537 ///
538 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
539   // If this is a noop copy,
540   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
541   EVT DstVT = TLI.getValueType(CI->getType());
542
543   // This is an fp<->int conversion?
544   if (SrcVT.isInteger() != DstVT.isInteger())
545     return false;
546
547   // If this is an extension, it will be a zero or sign extension, which
548   // isn't a noop.
549   if (SrcVT.bitsLT(DstVT)) return false;
550
551   // If these values will be promoted, find out what they will be promoted
552   // to.  This helps us consider truncates on PPC as noop copies when they
553   // are.
554   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
555       TargetLowering::TypePromoteInteger)
556     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
557   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
558       TargetLowering::TypePromoteInteger)
559     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
560
561   // If, after promotion, these are the same types, this is a noop copy.
562   if (SrcVT != DstVT)
563     return false;
564
565   return SinkCast(CI);
566 }
567
568 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
569 /// the number of virtual registers that must be created and coalesced.  This is
570 /// a clear win except on targets with multiple condition code registers
571 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
572 ///
573 /// Return true if any changes are made.
574 static bool OptimizeCmpExpression(CmpInst *CI) {
575   BasicBlock *DefBB = CI->getParent();
576
577   /// InsertedCmp - Only insert a cmp in each block once.
578   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
579
580   bool MadeChange = false;
581   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
582        UI != E; ) {
583     Use &TheUse = UI.getUse();
584     Instruction *User = cast<Instruction>(*UI);
585
586     // Preincrement use iterator so we don't invalidate it.
587     ++UI;
588
589     // Don't bother for PHI nodes.
590     if (isa<PHINode>(User))
591       continue;
592
593     // Figure out which BB this cmp is used in.
594     BasicBlock *UserBB = User->getParent();
595
596     // If this user is in the same block as the cmp, don't change the cmp.
597     if (UserBB == DefBB) continue;
598
599     // If we have already inserted a cmp into this block, use it.
600     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
601
602     if (!InsertedCmp) {
603       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
604       InsertedCmp =
605         CmpInst::Create(CI->getOpcode(),
606                         CI->getPredicate(),  CI->getOperand(0),
607                         CI->getOperand(1), "", InsertPt);
608       MadeChange = true;
609     }
610
611     // Replace a use of the cmp with a use of the new cmp.
612     TheUse = InsertedCmp;
613     ++NumCmpUses;
614   }
615
616   // If we removed all uses, nuke the cmp.
617   if (CI->use_empty())
618     CI->eraseFromParent();
619
620   return MadeChange;
621 }
622
623 namespace {
624 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
625 protected:
626   void replaceCall(Value *With) override {
627     CI->replaceAllUsesWith(With);
628     CI->eraseFromParent();
629   }
630   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
631       if (ConstantInt *SizeCI =
632                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
633         return SizeCI->isAllOnesValue();
634     return false;
635   }
636 };
637 } // end anonymous namespace
638
639 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
640   BasicBlock *BB = CI->getParent();
641
642   // Lower inline assembly if we can.
643   // If we found an inline asm expession, and if the target knows how to
644   // lower it to normal LLVM code, do so now.
645   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
646     if (TLI->ExpandInlineAsm(CI)) {
647       // Avoid invalidating the iterator.
648       CurInstIterator = BB->begin();
649       // Avoid processing instructions out of order, which could cause
650       // reuse before a value is defined.
651       SunkAddrs.clear();
652       return true;
653     }
654     // Sink address computing for memory operands into the block.
655     if (OptimizeInlineAsmInst(CI))
656       return true;
657   }
658
659   // Lower all uses of llvm.objectsize.*
660   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
661   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
662     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
663     Type *ReturnTy = CI->getType();
664     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
665
666     // Substituting this can cause recursive simplifications, which can
667     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
668     // happens.
669     WeakVH IterHandle(CurInstIterator);
670
671     replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
672                                   TLInfo, ModifiedDT ? 0 : DT);
673
674     // If the iterator instruction was recursively deleted, start over at the
675     // start of the block.
676     if (IterHandle != CurInstIterator) {
677       CurInstIterator = BB->begin();
678       SunkAddrs.clear();
679     }
680     return true;
681   }
682
683   if (II && TLI) {
684     SmallVector<Value*, 2> PtrOps;
685     Type *AccessTy;
686     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
687       while (!PtrOps.empty())
688         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
689           return true;
690   }
691
692   // From here on out we're working with named functions.
693   if (CI->getCalledFunction() == 0) return false;
694
695   // We'll need DataLayout from here on out.
696   const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
697   if (!TD) return false;
698
699   // Lower all default uses of _chk calls.  This is very similar
700   // to what InstCombineCalls does, but here we are only lowering calls
701   // that have the default "don't know" as the objectsize.  Anything else
702   // should be left alone.
703   CodeGenPrepareFortifiedLibCalls Simplifier;
704   return Simplifier.fold(CI, TD, TLInfo);
705 }
706
707 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
708 /// instructions to the predecessor to enable tail call optimizations. The
709 /// case it is currently looking for is:
710 /// @code
711 /// bb0:
712 ///   %tmp0 = tail call i32 @f0()
713 ///   br label %return
714 /// bb1:
715 ///   %tmp1 = tail call i32 @f1()
716 ///   br label %return
717 /// bb2:
718 ///   %tmp2 = tail call i32 @f2()
719 ///   br label %return
720 /// return:
721 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
722 ///   ret i32 %retval
723 /// @endcode
724 ///
725 /// =>
726 ///
727 /// @code
728 /// bb0:
729 ///   %tmp0 = tail call i32 @f0()
730 ///   ret i32 %tmp0
731 /// bb1:
732 ///   %tmp1 = tail call i32 @f1()
733 ///   ret i32 %tmp1
734 /// bb2:
735 ///   %tmp2 = tail call i32 @f2()
736 ///   ret i32 %tmp2
737 /// @endcode
738 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
739   if (!TLI)
740     return false;
741
742   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
743   if (!RI)
744     return false;
745
746   PHINode *PN = 0;
747   BitCastInst *BCI = 0;
748   Value *V = RI->getReturnValue();
749   if (V) {
750     BCI = dyn_cast<BitCastInst>(V);
751     if (BCI)
752       V = BCI->getOperand(0);
753
754     PN = dyn_cast<PHINode>(V);
755     if (!PN)
756       return false;
757   }
758
759   if (PN && PN->getParent() != BB)
760     return false;
761
762   // It's not safe to eliminate the sign / zero extension of the return value.
763   // See llvm::isInTailCallPosition().
764   const Function *F = BB->getParent();
765   AttributeSet CallerAttrs = F->getAttributes();
766   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
767       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
768     return false;
769
770   // Make sure there are no instructions between the PHI and return, or that the
771   // return is the first instruction in the block.
772   if (PN) {
773     BasicBlock::iterator BI = BB->begin();
774     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
775     if (&*BI == BCI)
776       // Also skip over the bitcast.
777       ++BI;
778     if (&*BI != RI)
779       return false;
780   } else {
781     BasicBlock::iterator BI = BB->begin();
782     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
783     if (&*BI != RI)
784       return false;
785   }
786
787   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
788   /// call.
789   SmallVector<CallInst*, 4> TailCalls;
790   if (PN) {
791     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
792       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
793       // Make sure the phi value is indeed produced by the tail call.
794       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
795           TLI->mayBeEmittedAsTailCall(CI))
796         TailCalls.push_back(CI);
797     }
798   } else {
799     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
800     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
801       if (!VisitedBBs.insert(*PI))
802         continue;
803
804       BasicBlock::InstListType &InstList = (*PI)->getInstList();
805       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
806       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
807       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
808       if (RI == RE)
809         continue;
810
811       CallInst *CI = dyn_cast<CallInst>(&*RI);
812       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
813         TailCalls.push_back(CI);
814     }
815   }
816
817   bool Changed = false;
818   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
819     CallInst *CI = TailCalls[i];
820     CallSite CS(CI);
821
822     // Conservatively require the attributes of the call to match those of the
823     // return. Ignore noalias because it doesn't affect the call sequence.
824     AttributeSet CalleeAttrs = CS.getAttributes();
825     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
826           removeAttribute(Attribute::NoAlias) !=
827         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
828           removeAttribute(Attribute::NoAlias))
829       continue;
830
831     // Make sure the call instruction is followed by an unconditional branch to
832     // the return block.
833     BasicBlock *CallBB = CI->getParent();
834     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
835     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
836       continue;
837
838     // Duplicate the return into CallBB.
839     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
840     ModifiedDT = Changed = true;
841     ++NumRetsDup;
842   }
843
844   // If we eliminated all predecessors of the block, delete the block now.
845   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
846     BB->eraseFromParent();
847
848   return Changed;
849 }
850
851 //===----------------------------------------------------------------------===//
852 // Memory Optimization
853 //===----------------------------------------------------------------------===//
854
855 namespace {
856
857 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
858 /// which holds actual Value*'s for register values.
859 struct ExtAddrMode : public TargetLowering::AddrMode {
860   Value *BaseReg;
861   Value *ScaledReg;
862   ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
863   void print(raw_ostream &OS) const;
864   void dump() const;
865
866   bool operator==(const ExtAddrMode& O) const {
867     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
868            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
869            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
870   }
871 };
872
873 #ifndef NDEBUG
874 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
875   AM.print(OS);
876   return OS;
877 }
878 #endif
879
880 void ExtAddrMode::print(raw_ostream &OS) const {
881   bool NeedPlus = false;
882   OS << "[";
883   if (BaseGV) {
884     OS << (NeedPlus ? " + " : "")
885        << "GV:";
886     BaseGV->printAsOperand(OS, /*PrintType=*/false);
887     NeedPlus = true;
888   }
889
890   if (BaseOffs)
891     OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
892
893   if (BaseReg) {
894     OS << (NeedPlus ? " + " : "")
895        << "Base:";
896     BaseReg->printAsOperand(OS, /*PrintType=*/false);
897     NeedPlus = true;
898   }
899   if (Scale) {
900     OS << (NeedPlus ? " + " : "")
901        << Scale << "*";
902     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
903   }
904
905   OS << ']';
906 }
907
908 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
909 void ExtAddrMode::dump() const {
910   print(dbgs());
911   dbgs() << '\n';
912 }
913 #endif
914
915 /// \brief This class provides transaction based operation on the IR.
916 /// Every change made through this class is recorded in the internal state and
917 /// can be undone (rollback) until commit is called.
918 class TypePromotionTransaction {
919
920   /// \brief This represents the common interface of the individual transaction.
921   /// Each class implements the logic for doing one specific modification on
922   /// the IR via the TypePromotionTransaction.
923   class TypePromotionAction {
924   protected:
925     /// The Instruction modified.
926     Instruction *Inst;
927
928   public:
929     /// \brief Constructor of the action.
930     /// The constructor performs the related action on the IR.
931     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
932
933     virtual ~TypePromotionAction() {}
934
935     /// \brief Undo the modification done by this action.
936     /// When this method is called, the IR must be in the same state as it was
937     /// before this action was applied.
938     /// \pre Undoing the action works if and only if the IR is in the exact same
939     /// state as it was directly after this action was applied.
940     virtual void undo() = 0;
941
942     /// \brief Advocate every change made by this action.
943     /// When the results on the IR of the action are to be kept, it is important
944     /// to call this function, otherwise hidden information may be kept forever.
945     virtual void commit() {
946       // Nothing to be done, this action is not doing anything.
947     }
948   };
949
950   /// \brief Utility to remember the position of an instruction.
951   class InsertionHandler {
952     /// Position of an instruction.
953     /// Either an instruction:
954     /// - Is the first in a basic block: BB is used.
955     /// - Has a previous instructon: PrevInst is used.
956     union {
957       Instruction *PrevInst;
958       BasicBlock *BB;
959     } Point;
960     /// Remember whether or not the instruction had a previous instruction.
961     bool HasPrevInstruction;
962
963   public:
964     /// \brief Record the position of \p Inst.
965     InsertionHandler(Instruction *Inst) {
966       BasicBlock::iterator It = Inst;
967       HasPrevInstruction = (It != (Inst->getParent()->begin()));
968       if (HasPrevInstruction)
969         Point.PrevInst = --It;
970       else
971         Point.BB = Inst->getParent();
972     }
973
974     /// \brief Insert \p Inst at the recorded position.
975     void insert(Instruction *Inst) {
976       if (HasPrevInstruction) {
977         if (Inst->getParent())
978           Inst->removeFromParent();
979         Inst->insertAfter(Point.PrevInst);
980       } else {
981         Instruction *Position = Point.BB->getFirstInsertionPt();
982         if (Inst->getParent())
983           Inst->moveBefore(Position);
984         else
985           Inst->insertBefore(Position);
986       }
987     }
988   };
989
990   /// \brief Move an instruction before another.
991   class InstructionMoveBefore : public TypePromotionAction {
992     /// Original position of the instruction.
993     InsertionHandler Position;
994
995   public:
996     /// \brief Move \p Inst before \p Before.
997     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
998         : TypePromotionAction(Inst), Position(Inst) {
999       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1000       Inst->moveBefore(Before);
1001     }
1002
1003     /// \brief Move the instruction back to its original position.
1004     void undo() override {
1005       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1006       Position.insert(Inst);
1007     }
1008   };
1009
1010   /// \brief Set the operand of an instruction with a new value.
1011   class OperandSetter : public TypePromotionAction {
1012     /// Original operand of the instruction.
1013     Value *Origin;
1014     /// Index of the modified instruction.
1015     unsigned Idx;
1016
1017   public:
1018     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1019     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1020         : TypePromotionAction(Inst), Idx(Idx) {
1021       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1022                    << "for:" << *Inst << "\n"
1023                    << "with:" << *NewVal << "\n");
1024       Origin = Inst->getOperand(Idx);
1025       Inst->setOperand(Idx, NewVal);
1026     }
1027
1028     /// \brief Restore the original value of the instruction.
1029     void undo() override {
1030       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1031                    << "for: " << *Inst << "\n"
1032                    << "with: " << *Origin << "\n");
1033       Inst->setOperand(Idx, Origin);
1034     }
1035   };
1036
1037   /// \brief Hide the operands of an instruction.
1038   /// Do as if this instruction was not using any of its operands.
1039   class OperandsHider : public TypePromotionAction {
1040     /// The list of original operands.
1041     SmallVector<Value *, 4> OriginalValues;
1042
1043   public:
1044     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1045     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1046       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1047       unsigned NumOpnds = Inst->getNumOperands();
1048       OriginalValues.reserve(NumOpnds);
1049       for (unsigned It = 0; It < NumOpnds; ++It) {
1050         // Save the current operand.
1051         Value *Val = Inst->getOperand(It);
1052         OriginalValues.push_back(Val);
1053         // Set a dummy one.
1054         // We could use OperandSetter here, but that would implied an overhead
1055         // that we are not willing to pay.
1056         Inst->setOperand(It, UndefValue::get(Val->getType()));
1057       }
1058     }
1059
1060     /// \brief Restore the original list of uses.
1061     void undo() override {
1062       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1063       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1064         Inst->setOperand(It, OriginalValues[It]);
1065     }
1066   };
1067
1068   /// \brief Build a truncate instruction.
1069   class TruncBuilder : public TypePromotionAction {
1070   public:
1071     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1072     /// result.
1073     /// trunc Opnd to Ty.
1074     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1075       IRBuilder<> Builder(Opnd);
1076       Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1077       DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1078     }
1079
1080     /// \brief Get the built instruction.
1081     Instruction *getBuiltInstruction() { return Inst; }
1082
1083     /// \brief Remove the built instruction.
1084     void undo() override {
1085       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1086       Inst->eraseFromParent();
1087     }
1088   };
1089
1090   /// \brief Build a sign extension instruction.
1091   class SExtBuilder : public TypePromotionAction {
1092   public:
1093     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1094     /// result.
1095     /// sext Opnd to Ty.
1096     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1097         : TypePromotionAction(Inst) {
1098       IRBuilder<> Builder(InsertPt);
1099       Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1100       DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1101     }
1102
1103     /// \brief Get the built instruction.
1104     Instruction *getBuiltInstruction() { return Inst; }
1105
1106     /// \brief Remove the built instruction.
1107     void undo() override {
1108       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1109       Inst->eraseFromParent();
1110     }
1111   };
1112
1113   /// \brief Mutate an instruction to another type.
1114   class TypeMutator : public TypePromotionAction {
1115     /// Record the original type.
1116     Type *OrigTy;
1117
1118   public:
1119     /// \brief Mutate the type of \p Inst into \p NewTy.
1120     TypeMutator(Instruction *Inst, Type *NewTy)
1121         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1122       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1123                    << "\n");
1124       Inst->mutateType(NewTy);
1125     }
1126
1127     /// \brief Mutate the instruction back to its original type.
1128     void undo() override {
1129       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1130                    << "\n");
1131       Inst->mutateType(OrigTy);
1132     }
1133   };
1134
1135   /// \brief Replace the uses of an instruction by another instruction.
1136   class UsesReplacer : public TypePromotionAction {
1137     /// Helper structure to keep track of the replaced uses.
1138     struct InstructionAndIdx {
1139       /// The instruction using the instruction.
1140       Instruction *Inst;
1141       /// The index where this instruction is used for Inst.
1142       unsigned Idx;
1143       InstructionAndIdx(Instruction *Inst, unsigned Idx)
1144           : Inst(Inst), Idx(Idx) {}
1145     };
1146
1147     /// Keep track of the original uses (pair Instruction, Index).
1148     SmallVector<InstructionAndIdx, 4> OriginalUses;
1149     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1150
1151   public:
1152     /// \brief Replace all the use of \p Inst by \p New.
1153     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1154       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1155                    << "\n");
1156       // Record the original uses.
1157       for (Use &U : Inst->uses()) {
1158         Instruction *UserI = cast<Instruction>(U.getUser());
1159         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1160       }
1161       // Now, we can replace the uses.
1162       Inst->replaceAllUsesWith(New);
1163     }
1164
1165     /// \brief Reassign the original uses of Inst to Inst.
1166     void undo() override {
1167       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1168       for (use_iterator UseIt = OriginalUses.begin(),
1169                         EndIt = OriginalUses.end();
1170            UseIt != EndIt; ++UseIt) {
1171         UseIt->Inst->setOperand(UseIt->Idx, Inst);
1172       }
1173     }
1174   };
1175
1176   /// \brief Remove an instruction from the IR.
1177   class InstructionRemover : public TypePromotionAction {
1178     /// Original position of the instruction.
1179     InsertionHandler Inserter;
1180     /// Helper structure to hide all the link to the instruction. In other
1181     /// words, this helps to do as if the instruction was removed.
1182     OperandsHider Hider;
1183     /// Keep track of the uses replaced, if any.
1184     UsesReplacer *Replacer;
1185
1186   public:
1187     /// \brief Remove all reference of \p Inst and optinally replace all its
1188     /// uses with New.
1189     /// \pre If !Inst->use_empty(), then New != NULL
1190     InstructionRemover(Instruction *Inst, Value *New = NULL)
1191         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1192           Replacer(NULL) {
1193       if (New)
1194         Replacer = new UsesReplacer(Inst, New);
1195       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1196       Inst->removeFromParent();
1197     }
1198
1199     ~InstructionRemover() { delete Replacer; }
1200
1201     /// \brief Really remove the instruction.
1202     void commit() override { delete Inst; }
1203
1204     /// \brief Resurrect the instruction and reassign it to the proper uses if
1205     /// new value was provided when build this action.
1206     void undo() override {
1207       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1208       Inserter.insert(Inst);
1209       if (Replacer)
1210         Replacer->undo();
1211       Hider.undo();
1212     }
1213   };
1214
1215 public:
1216   /// Restoration point.
1217   /// The restoration point is a pointer to an action instead of an iterator
1218   /// because the iterator may be invalidated but not the pointer.
1219   typedef const TypePromotionAction *ConstRestorationPt;
1220   /// Advocate every changes made in that transaction.
1221   void commit();
1222   /// Undo all the changes made after the given point.
1223   void rollback(ConstRestorationPt Point);
1224   /// Get the current restoration point.
1225   ConstRestorationPt getRestorationPoint() const;
1226
1227   /// \name API for IR modification with state keeping to support rollback.
1228   /// @{
1229   /// Same as Instruction::setOperand.
1230   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1231   /// Same as Instruction::eraseFromParent.
1232   void eraseInstruction(Instruction *Inst, Value *NewVal = NULL);
1233   /// Same as Value::replaceAllUsesWith.
1234   void replaceAllUsesWith(Instruction *Inst, Value *New);
1235   /// Same as Value::mutateType.
1236   void mutateType(Instruction *Inst, Type *NewTy);
1237   /// Same as IRBuilder::createTrunc.
1238   Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1239   /// Same as IRBuilder::createSExt.
1240   Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1241   /// Same as Instruction::moveBefore.
1242   void moveBefore(Instruction *Inst, Instruction *Before);
1243   /// @}
1244
1245   ~TypePromotionTransaction();
1246
1247 private:
1248   /// The ordered list of actions made so far.
1249   SmallVector<TypePromotionAction *, 16> Actions;
1250   typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1251 };
1252
1253 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1254                                           Value *NewVal) {
1255   Actions.push_back(
1256       new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1257 }
1258
1259 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1260                                                 Value *NewVal) {
1261   Actions.push_back(
1262       new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1263 }
1264
1265 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1266                                                   Value *New) {
1267   Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1268 }
1269
1270 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1271   Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1272 }
1273
1274 Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1275                                                    Type *Ty) {
1276   TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1277   Actions.push_back(TB);
1278   return TB->getBuiltInstruction();
1279 }
1280
1281 Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1282                                                   Value *Opnd, Type *Ty) {
1283   SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1284   Actions.push_back(SB);
1285   return SB->getBuiltInstruction();
1286 }
1287
1288 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1289                                           Instruction *Before) {
1290   Actions.push_back(
1291       new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1292 }
1293
1294 TypePromotionTransaction::ConstRestorationPt
1295 TypePromotionTransaction::getRestorationPoint() const {
1296   return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : NULL;
1297 }
1298
1299 void TypePromotionTransaction::commit() {
1300   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1301        ++It) {
1302     (*It)->commit();
1303     delete *It;
1304   }
1305   Actions.clear();
1306 }
1307
1308 void TypePromotionTransaction::rollback(
1309     TypePromotionTransaction::ConstRestorationPt Point) {
1310   while (!Actions.empty() && Point != (*Actions.rbegin())) {
1311     TypePromotionAction *Curr = Actions.pop_back_val();
1312     Curr->undo();
1313     delete Curr;
1314   }
1315 }
1316
1317 TypePromotionTransaction::~TypePromotionTransaction() {
1318   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1319     delete *It;
1320   Actions.clear();
1321 }
1322
1323 /// \brief A helper class for matching addressing modes.
1324 ///
1325 /// This encapsulates the logic for matching the target-legal addressing modes.
1326 class AddressingModeMatcher {
1327   SmallVectorImpl<Instruction*> &AddrModeInsts;
1328   const TargetLowering &TLI;
1329
1330   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1331   /// the memory instruction that we're computing this address for.
1332   Type *AccessTy;
1333   Instruction *MemoryInst;
1334
1335   /// AddrMode - This is the addressing mode that we're building up.  This is
1336   /// part of the return value of this addressing mode matching stuff.
1337   ExtAddrMode &AddrMode;
1338
1339   /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1340   const SetOfInstrs &InsertedTruncs;
1341   /// A map from the instructions to their type before promotion.
1342   InstrToOrigTy &PromotedInsts;
1343   /// The ongoing transaction where every action should be registered.
1344   TypePromotionTransaction &TPT;
1345
1346   /// IgnoreProfitability - This is set to true when we should not do
1347   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
1348   /// always returns true.
1349   bool IgnoreProfitability;
1350
1351   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1352                         const TargetLowering &T, Type *AT,
1353                         Instruction *MI, ExtAddrMode &AM,
1354                         const SetOfInstrs &InsertedTruncs,
1355                         InstrToOrigTy &PromotedInsts,
1356                         TypePromotionTransaction &TPT)
1357       : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1358         InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1359     IgnoreProfitability = false;
1360   }
1361 public:
1362
1363   /// Match - Find the maximal addressing mode that a load/store of V can fold,
1364   /// give an access type of AccessTy.  This returns a list of involved
1365   /// instructions in AddrModeInsts.
1366   /// \p InsertedTruncs The truncate instruction inserted by other
1367   /// CodeGenPrepare
1368   /// optimizations.
1369   /// \p PromotedInsts maps the instructions to their type before promotion.
1370   /// \p The ongoing transaction where every action should be registered.
1371   static ExtAddrMode Match(Value *V, Type *AccessTy,
1372                            Instruction *MemoryInst,
1373                            SmallVectorImpl<Instruction*> &AddrModeInsts,
1374                            const TargetLowering &TLI,
1375                            const SetOfInstrs &InsertedTruncs,
1376                            InstrToOrigTy &PromotedInsts,
1377                            TypePromotionTransaction &TPT) {
1378     ExtAddrMode Result;
1379
1380     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1381                                          MemoryInst, Result, InsertedTruncs,
1382                                          PromotedInsts, TPT).MatchAddr(V, 0);
1383     (void)Success; assert(Success && "Couldn't select *anything*?");
1384     return Result;
1385   }
1386 private:
1387   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1388   bool MatchAddr(Value *V, unsigned Depth);
1389   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1390                           bool *MovedAway = NULL);
1391   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1392                                             ExtAddrMode &AMBefore,
1393                                             ExtAddrMode &AMAfter);
1394   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1395   bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1396                              Value *PromotedOperand) const;
1397 };
1398
1399 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1400 /// Return true and update AddrMode if this addr mode is legal for the target,
1401 /// false if not.
1402 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1403                                              unsigned Depth) {
1404   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1405   // mode.  Just process that directly.
1406   if (Scale == 1)
1407     return MatchAddr(ScaleReg, Depth);
1408
1409   // If the scale is 0, it takes nothing to add this.
1410   if (Scale == 0)
1411     return true;
1412
1413   // If we already have a scale of this value, we can add to it, otherwise, we
1414   // need an available scale field.
1415   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1416     return false;
1417
1418   ExtAddrMode TestAddrMode = AddrMode;
1419
1420   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
1421   // [A+B + A*7] -> [B+A*8].
1422   TestAddrMode.Scale += Scale;
1423   TestAddrMode.ScaledReg = ScaleReg;
1424
1425   // If the new address isn't legal, bail out.
1426   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1427     return false;
1428
1429   // It was legal, so commit it.
1430   AddrMode = TestAddrMode;
1431
1432   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
1433   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
1434   // X*Scale + C*Scale to addr mode.
1435   ConstantInt *CI = 0; Value *AddLHS = 0;
1436   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
1437       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1438     TestAddrMode.ScaledReg = AddLHS;
1439     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1440
1441     // If this addressing mode is legal, commit it and remember that we folded
1442     // this instruction.
1443     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1444       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1445       AddrMode = TestAddrMode;
1446       return true;
1447     }
1448   }
1449
1450   // Otherwise, not (x+c)*scale, just return what we have.
1451   return true;
1452 }
1453
1454 /// MightBeFoldableInst - This is a little filter, which returns true if an
1455 /// addressing computation involving I might be folded into a load/store
1456 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
1457 /// the set of instructions that MatchOperationAddr can.
1458 static bool MightBeFoldableInst(Instruction *I) {
1459   switch (I->getOpcode()) {
1460   case Instruction::BitCast:
1461     // Don't touch identity bitcasts.
1462     if (I->getType() == I->getOperand(0)->getType())
1463       return false;
1464     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1465   case Instruction::PtrToInt:
1466     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1467     return true;
1468   case Instruction::IntToPtr:
1469     // We know the input is intptr_t, so this is foldable.
1470     return true;
1471   case Instruction::Add:
1472     return true;
1473   case Instruction::Mul:
1474   case Instruction::Shl:
1475     // Can only handle X*C and X << C.
1476     return isa<ConstantInt>(I->getOperand(1));
1477   case Instruction::GetElementPtr:
1478     return true;
1479   default:
1480     return false;
1481   }
1482 }
1483
1484 /// \brief Hepler class to perform type promotion.
1485 class TypePromotionHelper {
1486   /// \brief Utility function to check whether or not a sign extension of
1487   /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1488   /// using the operands of \p Inst or promoting \p Inst.
1489   /// In other words, check if:
1490   /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1491   /// #1 Promotion applies:
1492   /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1493   /// #2 Operand reuses:
1494   /// sext opnd1 to ConsideredSExtType.
1495   /// \p PromotedInsts maps the instructions to their type before promotion.
1496   static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1497                             const InstrToOrigTy &PromotedInsts);
1498
1499   /// \brief Utility function to determine if \p OpIdx should be promoted when
1500   /// promoting \p Inst.
1501   static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1502     if (isa<SelectInst>(Inst) && OpIdx == 0)
1503       return false;
1504     return true;
1505   }
1506
1507   /// \brief Utility function to promote the operand of \p SExt when this
1508   /// operand is a promotable trunc or sext.
1509   /// \p PromotedInsts maps the instructions to their type before promotion.
1510   /// \p CreatedInsts[out] contains how many non-free instructions have been
1511   /// created to promote the operand of SExt.
1512   /// Should never be called directly.
1513   /// \return The promoted value which is used instead of SExt.
1514   static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1515                                               TypePromotionTransaction &TPT,
1516                                               InstrToOrigTy &PromotedInsts,
1517                                               unsigned &CreatedInsts);
1518
1519   /// \brief Utility function to promote the operand of \p SExt when this
1520   /// operand is promotable and is not a supported trunc or sext.
1521   /// \p PromotedInsts maps the instructions to their type before promotion.
1522   /// \p CreatedInsts[out] contains how many non-free instructions have been
1523   /// created to promote the operand of SExt.
1524   /// Should never be called directly.
1525   /// \return The promoted value which is used instead of SExt.
1526   static Value *promoteOperandForOther(Instruction *SExt,
1527                                        TypePromotionTransaction &TPT,
1528                                        InstrToOrigTy &PromotedInsts,
1529                                        unsigned &CreatedInsts);
1530
1531 public:
1532   /// Type for the utility function that promotes the operand of SExt.
1533   typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1534                            InstrToOrigTy &PromotedInsts,
1535                            unsigned &CreatedInsts);
1536   /// \brief Given a sign extend instruction \p SExt, return the approriate
1537   /// action to promote the operand of \p SExt instead of using SExt.
1538   /// \return NULL if no promotable action is possible with the current
1539   /// sign extension.
1540   /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1541   /// the others CodeGenPrepare optimizations. This information is important
1542   /// because we do not want to promote these instructions as CodeGenPrepare
1543   /// will reinsert them later. Thus creating an infinite loop: create/remove.
1544   /// \p PromotedInsts maps the instructions to their type before promotion.
1545   static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1546                           const TargetLowering &TLI,
1547                           const InstrToOrigTy &PromotedInsts);
1548 };
1549
1550 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1551                                         Type *ConsideredSExtType,
1552                                         const InstrToOrigTy &PromotedInsts) {
1553   // We can always get through sext.
1554   if (isa<SExtInst>(Inst))
1555     return true;
1556
1557   // We can get through binary operator, if it is legal. In other words, the
1558   // binary operator must have a nuw or nsw flag.
1559   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1560   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1561       (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1562     return true;
1563
1564   // Check if we can do the following simplification.
1565   // sext(trunc(sext)) --> sext
1566   if (!isa<TruncInst>(Inst))
1567     return false;
1568
1569   Value *OpndVal = Inst->getOperand(0);
1570   // Check if we can use this operand in the sext.
1571   // If the type is larger than the result type of the sign extension,
1572   // we cannot.
1573   if (OpndVal->getType()->getIntegerBitWidth() >
1574       ConsideredSExtType->getIntegerBitWidth())
1575     return false;
1576
1577   // If the operand of the truncate is not an instruction, we will not have
1578   // any information on the dropped bits.
1579   // (Actually we could for constant but it is not worth the extra logic).
1580   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1581   if (!Opnd)
1582     return false;
1583
1584   // Check if the source of the type is narrow enough.
1585   // I.e., check that trunc just drops sign extended bits.
1586   // #1 get the type of the operand.
1587   const Type *OpndType;
1588   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1589   if (It != PromotedInsts.end())
1590     OpndType = It->second;
1591   else if (isa<SExtInst>(Opnd))
1592     OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1593   else
1594     return false;
1595
1596   // #2 check that the truncate just drop sign extended bits.
1597   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1598     return true;
1599
1600   return false;
1601 }
1602
1603 TypePromotionHelper::Action TypePromotionHelper::getAction(
1604     Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1605     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1606   Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1607   Type *SExtTy = SExt->getType();
1608   // If the operand of the sign extension is not an instruction, we cannot
1609   // get through.
1610   // If it, check we can get through.
1611   if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1612     return NULL;
1613
1614   // Do not promote if the operand has been added by codegenprepare.
1615   // Otherwise, it means we are undoing an optimization that is likely to be
1616   // redone, thus causing potential infinite loop.
1617   if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1618     return NULL;
1619
1620   // SExt or Trunc instructions.
1621   // Return the related handler.
1622   if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1623     return promoteOperandForTruncAndSExt;
1624
1625   // Regular instruction.
1626   // Abort early if we will have to insert non-free instructions.
1627   if (!SExtOpnd->hasOneUse() &&
1628       !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1629     return NULL;
1630   return promoteOperandForOther;
1631 }
1632
1633 Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1634     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1635     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1636   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1637   // get through it and this method should not be called.
1638   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1639   // Replace sext(trunc(opnd)) or sext(sext(opnd))
1640   // => sext(opnd).
1641   TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1642   CreatedInsts = 0;
1643
1644   // Remove dead code.
1645   if (SExtOpnd->use_empty())
1646     TPT.eraseInstruction(SExtOpnd);
1647
1648   // Check if the sext is still needed.
1649   if (SExt->getType() != SExt->getOperand(0)->getType())
1650     return SExt;
1651
1652   // At this point we have: sext ty opnd to ty.
1653   // Reassign the uses of SExt to the opnd and remove SExt.
1654   Value *NextVal = SExt->getOperand(0);
1655   TPT.eraseInstruction(SExt, NextVal);
1656   return NextVal;
1657 }
1658
1659 Value *
1660 TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1661                                             TypePromotionTransaction &TPT,
1662                                             InstrToOrigTy &PromotedInsts,
1663                                             unsigned &CreatedInsts) {
1664   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1665   // get through it and this method should not be called.
1666   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1667   CreatedInsts = 0;
1668   if (!SExtOpnd->hasOneUse()) {
1669     // SExtOpnd will be promoted.
1670     // All its uses, but SExt, will need to use a truncated value of the
1671     // promoted version.
1672     // Create the truncate now.
1673     Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1674     Trunc->removeFromParent();
1675     // Insert it just after the definition.
1676     Trunc->insertAfter(SExtOpnd);
1677
1678     TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1679     // Restore the operand of SExt (which has been replace by the previous call
1680     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1681     TPT.setOperand(SExt, 0, SExtOpnd);
1682   }
1683
1684   // Get through the Instruction:
1685   // 1. Update its type.
1686   // 2. Replace the uses of SExt by Inst.
1687   // 3. Sign extend each operand that needs to be sign extended.
1688
1689   // Remember the original type of the instruction before promotion.
1690   // This is useful to know that the high bits are sign extended bits.
1691   PromotedInsts.insert(
1692       std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1693   // Step #1.
1694   TPT.mutateType(SExtOpnd, SExt->getType());
1695   // Step #2.
1696   TPT.replaceAllUsesWith(SExt, SExtOpnd);
1697   // Step #3.
1698   Instruction *SExtForOpnd = SExt;
1699
1700   DEBUG(dbgs() << "Propagate SExt to operands\n");
1701   for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1702        ++OpIdx) {
1703     DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1704     if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1705         !shouldSExtOperand(SExtOpnd, OpIdx)) {
1706       DEBUG(dbgs() << "No need to propagate\n");
1707       continue;
1708     }
1709     // Check if we can statically sign extend the operand.
1710     Value *Opnd = SExtOpnd->getOperand(OpIdx);
1711     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1712       DEBUG(dbgs() << "Statically sign extend\n");
1713       TPT.setOperand(
1714           SExtOpnd, OpIdx,
1715           ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1716       continue;
1717     }
1718     // UndefValue are typed, so we have to statically sign extend them.
1719     if (isa<UndefValue>(Opnd)) {
1720       DEBUG(dbgs() << "Statically sign extend\n");
1721       TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1722       continue;
1723     }
1724
1725     // Otherwise we have to explicity sign extend the operand.
1726     // Check if SExt was reused to sign extend an operand.
1727     if (!SExtForOpnd) {
1728       // If yes, create a new one.
1729       DEBUG(dbgs() << "More operands to sext\n");
1730       SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1731       ++CreatedInsts;
1732     }
1733
1734     TPT.setOperand(SExtForOpnd, 0, Opnd);
1735
1736     // Move the sign extension before the insertion point.
1737     TPT.moveBefore(SExtForOpnd, SExtOpnd);
1738     TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1739     // If more sext are required, new instructions will have to be created.
1740     SExtForOpnd = NULL;
1741   }
1742   if (SExtForOpnd == SExt) {
1743     DEBUG(dbgs() << "Sign extension is useless now\n");
1744     TPT.eraseInstruction(SExt);
1745   }
1746   return SExtOpnd;
1747 }
1748
1749 /// IsPromotionProfitable - Check whether or not promoting an instruction
1750 /// to a wider type was profitable.
1751 /// \p MatchedSize gives the number of instructions that have been matched
1752 /// in the addressing mode after the promotion was applied.
1753 /// \p SizeWithPromotion gives the number of created instructions for
1754 /// the promotion plus the number of instructions that have been
1755 /// matched in the addressing mode before the promotion.
1756 /// \p PromotedOperand is the value that has been promoted.
1757 /// \return True if the promotion is profitable, false otherwise.
1758 bool
1759 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1760                                              unsigned SizeWithPromotion,
1761                                              Value *PromotedOperand) const {
1762   // We folded less instructions than what we created to promote the operand.
1763   // This is not profitable.
1764   if (MatchedSize < SizeWithPromotion)
1765     return false;
1766   if (MatchedSize > SizeWithPromotion)
1767     return true;
1768   // The promotion is neutral but it may help folding the sign extension in
1769   // loads for instance.
1770   // Check that we did not create an illegal instruction.
1771   Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1772   if (!PromotedInst)
1773     return false;
1774   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1775   // If the ISDOpcode is undefined, it was undefined before the promotion.
1776   if (!ISDOpcode)
1777     return true;
1778   // Otherwise, check if the promoted instruction is legal or not.
1779   return TLI.isOperationLegalOrCustom(ISDOpcode,
1780                                       EVT::getEVT(PromotedInst->getType()));
1781 }
1782
1783 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
1784 /// fold the operation into the addressing mode.  If so, update the addressing
1785 /// mode and return true, otherwise return false without modifying AddrMode.
1786 /// If \p MovedAway is not NULL, it contains the information of whether or
1787 /// not AddrInst has to be folded into the addressing mode on success.
1788 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1789 /// because it has been moved away.
1790 /// Thus AddrInst must not be added in the matched instructions.
1791 /// This state can happen when AddrInst is a sext, since it may be moved away.
1792 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
1793 /// not be referenced anymore.
1794 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1795                                                unsigned Depth,
1796                                                bool *MovedAway) {
1797   // Avoid exponential behavior on extremely deep expression trees.
1798   if (Depth >= 5) return false;
1799
1800   // By default, all matched instructions stay in place.
1801   if (MovedAway)
1802     *MovedAway = false;
1803
1804   switch (Opcode) {
1805   case Instruction::PtrToInt:
1806     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1807     return MatchAddr(AddrInst->getOperand(0), Depth);
1808   case Instruction::IntToPtr:
1809     // This inttoptr is a no-op if the integer type is pointer sized.
1810     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
1811         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
1812       return MatchAddr(AddrInst->getOperand(0), Depth);
1813     return false;
1814   case Instruction::BitCast:
1815     // BitCast is always a noop, and we can handle it as long as it is
1816     // int->int or pointer->pointer (we don't want int<->fp or something).
1817     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1818          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1819         // Don't touch identity bitcasts.  These were probably put here by LSR,
1820         // and we don't want to mess around with them.  Assume it knows what it
1821         // is doing.
1822         AddrInst->getOperand(0)->getType() != AddrInst->getType())
1823       return MatchAddr(AddrInst->getOperand(0), Depth);
1824     return false;
1825   case Instruction::Add: {
1826     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
1827     ExtAddrMode BackupAddrMode = AddrMode;
1828     unsigned OldSize = AddrModeInsts.size();
1829     // Start a transaction at this point.
1830     // The LHS may match but not the RHS.
1831     // Therefore, we need a higher level restoration point to undo partially
1832     // matched operation.
1833     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1834         TPT.getRestorationPoint();
1835
1836     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1837         MatchAddr(AddrInst->getOperand(0), Depth+1))
1838       return true;
1839
1840     // Restore the old addr mode info.
1841     AddrMode = BackupAddrMode;
1842     AddrModeInsts.resize(OldSize);
1843     TPT.rollback(LastKnownGood);
1844
1845     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
1846     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1847         MatchAddr(AddrInst->getOperand(1), Depth+1))
1848       return true;
1849
1850     // Otherwise we definitely can't merge the ADD in.
1851     AddrMode = BackupAddrMode;
1852     AddrModeInsts.resize(OldSize);
1853     TPT.rollback(LastKnownGood);
1854     break;
1855   }
1856   //case Instruction::Or:
1857   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1858   //break;
1859   case Instruction::Mul:
1860   case Instruction::Shl: {
1861     // Can only handle X*C and X << C.
1862     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1863     if (!RHS) return false;
1864     int64_t Scale = RHS->getSExtValue();
1865     if (Opcode == Instruction::Shl)
1866       Scale = 1LL << Scale;
1867
1868     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1869   }
1870   case Instruction::GetElementPtr: {
1871     // Scan the GEP.  We check it if it contains constant offsets and at most
1872     // one variable offset.
1873     int VariableOperand = -1;
1874     unsigned VariableScale = 0;
1875
1876     int64_t ConstantOffset = 0;
1877     const DataLayout *TD = TLI.getDataLayout();
1878     gep_type_iterator GTI = gep_type_begin(AddrInst);
1879     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1880       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1881         const StructLayout *SL = TD->getStructLayout(STy);
1882         unsigned Idx =
1883           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1884         ConstantOffset += SL->getElementOffset(Idx);
1885       } else {
1886         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1887         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1888           ConstantOffset += CI->getSExtValue()*TypeSize;
1889         } else if (TypeSize) {  // Scales of zero don't do anything.
1890           // We only allow one variable index at the moment.
1891           if (VariableOperand != -1)
1892             return false;
1893
1894           // Remember the variable index.
1895           VariableOperand = i;
1896           VariableScale = TypeSize;
1897         }
1898       }
1899     }
1900
1901     // A common case is for the GEP to only do a constant offset.  In this case,
1902     // just add it to the disp field and check validity.
1903     if (VariableOperand == -1) {
1904       AddrMode.BaseOffs += ConstantOffset;
1905       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1906         // Check to see if we can fold the base pointer in too.
1907         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1908           return true;
1909       }
1910       AddrMode.BaseOffs -= ConstantOffset;
1911       return false;
1912     }
1913
1914     // Save the valid addressing mode in case we can't match.
1915     ExtAddrMode BackupAddrMode = AddrMode;
1916     unsigned OldSize = AddrModeInsts.size();
1917
1918     // See if the scale and offset amount is valid for this target.
1919     AddrMode.BaseOffs += ConstantOffset;
1920
1921     // Match the base operand of the GEP.
1922     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1923       // If it couldn't be matched, just stuff the value in a register.
1924       if (AddrMode.HasBaseReg) {
1925         AddrMode = BackupAddrMode;
1926         AddrModeInsts.resize(OldSize);
1927         return false;
1928       }
1929       AddrMode.HasBaseReg = true;
1930       AddrMode.BaseReg = AddrInst->getOperand(0);
1931     }
1932
1933     // Match the remaining variable portion of the GEP.
1934     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1935                           Depth)) {
1936       // If it couldn't be matched, try stuffing the base into a register
1937       // instead of matching it, and retrying the match of the scale.
1938       AddrMode = BackupAddrMode;
1939       AddrModeInsts.resize(OldSize);
1940       if (AddrMode.HasBaseReg)
1941         return false;
1942       AddrMode.HasBaseReg = true;
1943       AddrMode.BaseReg = AddrInst->getOperand(0);
1944       AddrMode.BaseOffs += ConstantOffset;
1945       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1946                             VariableScale, Depth)) {
1947         // If even that didn't work, bail.
1948         AddrMode = BackupAddrMode;
1949         AddrModeInsts.resize(OldSize);
1950         return false;
1951       }
1952     }
1953
1954     return true;
1955   }
1956   case Instruction::SExt: {
1957     // Try to move this sext out of the way of the addressing mode.
1958     Instruction *SExt = cast<Instruction>(AddrInst);
1959     // Ask for a method for doing so.
1960     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1961         SExt, InsertedTruncs, TLI, PromotedInsts);
1962     if (!TPH)
1963       return false;
1964
1965     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1966         TPT.getRestorationPoint();
1967     unsigned CreatedInsts = 0;
1968     Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1969     // SExt has been moved away.
1970     // Thus either it will be rematched later in the recursive calls or it is
1971     // gone. Anyway, we must not fold it into the addressing mode at this point.
1972     // E.g.,
1973     // op = add opnd, 1
1974     // idx = sext op
1975     // addr = gep base, idx
1976     // is now:
1977     // promotedOpnd = sext opnd           <- no match here
1978     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
1979     // addr = gep base, op                <- match
1980     if (MovedAway)
1981       *MovedAway = true;
1982
1983     assert(PromotedOperand &&
1984            "TypePromotionHelper should have filtered out those cases");
1985
1986     ExtAddrMode BackupAddrMode = AddrMode;
1987     unsigned OldSize = AddrModeInsts.size();
1988
1989     if (!MatchAddr(PromotedOperand, Depth) ||
1990         !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
1991                                PromotedOperand)) {
1992       AddrMode = BackupAddrMode;
1993       AddrModeInsts.resize(OldSize);
1994       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
1995       TPT.rollback(LastKnownGood);
1996       return false;
1997     }
1998     return true;
1999   }
2000   }
2001   return false;
2002 }
2003
2004 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2005 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
2006 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
2007 /// or intptr_t for the target.
2008 ///
2009 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2010   // Start a transaction at this point that we will rollback if the matching
2011   // fails.
2012   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2013       TPT.getRestorationPoint();
2014   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2015     // Fold in immediates if legal for the target.
2016     AddrMode.BaseOffs += CI->getSExtValue();
2017     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2018       return true;
2019     AddrMode.BaseOffs -= CI->getSExtValue();
2020   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2021     // If this is a global variable, try to fold it into the addressing mode.
2022     if (AddrMode.BaseGV == 0) {
2023       AddrMode.BaseGV = GV;
2024       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2025         return true;
2026       AddrMode.BaseGV = 0;
2027     }
2028   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2029     ExtAddrMode BackupAddrMode = AddrMode;
2030     unsigned OldSize = AddrModeInsts.size();
2031
2032     // Check to see if it is possible to fold this operation.
2033     bool MovedAway = false;
2034     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2035       // This instruction may have been move away. If so, there is nothing
2036       // to check here.
2037       if (MovedAway)
2038         return true;
2039       // Okay, it's possible to fold this.  Check to see if it is actually
2040       // *profitable* to do so.  We use a simple cost model to avoid increasing
2041       // register pressure too much.
2042       if (I->hasOneUse() ||
2043           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2044         AddrModeInsts.push_back(I);
2045         return true;
2046       }
2047
2048       // It isn't profitable to do this, roll back.
2049       //cerr << "NOT FOLDING: " << *I;
2050       AddrMode = BackupAddrMode;
2051       AddrModeInsts.resize(OldSize);
2052       TPT.rollback(LastKnownGood);
2053     }
2054   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2055     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2056       return true;
2057     TPT.rollback(LastKnownGood);
2058   } else if (isa<ConstantPointerNull>(Addr)) {
2059     // Null pointer gets folded without affecting the addressing mode.
2060     return true;
2061   }
2062
2063   // Worse case, the target should support [reg] addressing modes. :)
2064   if (!AddrMode.HasBaseReg) {
2065     AddrMode.HasBaseReg = true;
2066     AddrMode.BaseReg = Addr;
2067     // Still check for legality in case the target supports [imm] but not [i+r].
2068     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2069       return true;
2070     AddrMode.HasBaseReg = false;
2071     AddrMode.BaseReg = 0;
2072   }
2073
2074   // If the base register is already taken, see if we can do [r+r].
2075   if (AddrMode.Scale == 0) {
2076     AddrMode.Scale = 1;
2077     AddrMode.ScaledReg = Addr;
2078     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2079       return true;
2080     AddrMode.Scale = 0;
2081     AddrMode.ScaledReg = 0;
2082   }
2083   // Couldn't match.
2084   TPT.rollback(LastKnownGood);
2085   return false;
2086 }
2087
2088 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2089 /// inline asm call are due to memory operands.  If so, return true, otherwise
2090 /// return false.
2091 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2092                                     const TargetLowering &TLI) {
2093   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2094   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2095     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2096
2097     // Compute the constraint code and ConstraintType to use.
2098     TLI.ComputeConstraintToUse(OpInfo, SDValue());
2099
2100     // If this asm operand is our Value*, and if it isn't an indirect memory
2101     // operand, we can't fold it!
2102     if (OpInfo.CallOperandVal == OpVal &&
2103         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2104          !OpInfo.isIndirect))
2105       return false;
2106   }
2107
2108   return true;
2109 }
2110
2111 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2112 /// memory use.  If we find an obviously non-foldable instruction, return true.
2113 /// Add the ultimately found memory instructions to MemoryUses.
2114 static bool FindAllMemoryUses(Instruction *I,
2115                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2116                               SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2117                               const TargetLowering &TLI) {
2118   // If we already considered this instruction, we're done.
2119   if (!ConsideredInsts.insert(I))
2120     return false;
2121
2122   // If this is an obviously unfoldable instruction, bail out.
2123   if (!MightBeFoldableInst(I))
2124     return true;
2125
2126   // Loop over all the uses, recursively processing them.
2127   for (Use &U : I->uses()) {
2128     Instruction *UserI = cast<Instruction>(U.getUser());
2129
2130     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2131       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2132       continue;
2133     }
2134
2135     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2136       unsigned opNo = U.getOperandNo();
2137       if (opNo == 0) return true; // Storing addr, not into addr.
2138       MemoryUses.push_back(std::make_pair(SI, opNo));
2139       continue;
2140     }
2141
2142     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2143       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2144       if (!IA) return true;
2145
2146       // If this is a memory operand, we're cool, otherwise bail out.
2147       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2148         return true;
2149       continue;
2150     }
2151
2152     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2153       return true;
2154   }
2155
2156   return false;
2157 }
2158
2159 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2160 /// the use site that we're folding it into.  If so, there is no cost to
2161 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
2162 /// that we know are live at the instruction already.
2163 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2164                                                    Value *KnownLive2) {
2165   // If Val is either of the known-live values, we know it is live!
2166   if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
2167     return true;
2168
2169   // All values other than instructions and arguments (e.g. constants) are live.
2170   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2171
2172   // If Val is a constant sized alloca in the entry block, it is live, this is
2173   // true because it is just a reference to the stack/frame pointer, which is
2174   // live for the whole function.
2175   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2176     if (AI->isStaticAlloca())
2177       return true;
2178
2179   // Check to see if this value is already used in the memory instruction's
2180   // block.  If so, it's already live into the block at the very least, so we
2181   // can reasonably fold it.
2182   return Val->isUsedInBasicBlock(MemoryInst->getParent());
2183 }
2184
2185 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2186 /// mode of the machine to fold the specified instruction into a load or store
2187 /// that ultimately uses it.  However, the specified instruction has multiple
2188 /// uses.  Given this, it may actually increase register pressure to fold it
2189 /// into the load.  For example, consider this code:
2190 ///
2191 ///     X = ...
2192 ///     Y = X+1
2193 ///     use(Y)   -> nonload/store
2194 ///     Z = Y+1
2195 ///     load Z
2196 ///
2197 /// In this case, Y has multiple uses, and can be folded into the load of Z
2198 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
2199 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
2200 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
2201 /// number of computations either.
2202 ///
2203 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
2204 /// X was live across 'load Z' for other reasons, we actually *would* want to
2205 /// fold the addressing mode in the Z case.  This would make Y die earlier.
2206 bool AddressingModeMatcher::
2207 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2208                                      ExtAddrMode &AMAfter) {
2209   if (IgnoreProfitability) return true;
2210
2211   // AMBefore is the addressing mode before this instruction was folded into it,
2212   // and AMAfter is the addressing mode after the instruction was folded.  Get
2213   // the set of registers referenced by AMAfter and subtract out those
2214   // referenced by AMBefore: this is the set of values which folding in this
2215   // address extends the lifetime of.
2216   //
2217   // Note that there are only two potential values being referenced here,
2218   // BaseReg and ScaleReg (global addresses are always available, as are any
2219   // folded immediates).
2220   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2221
2222   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2223   // lifetime wasn't extended by adding this instruction.
2224   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2225     BaseReg = 0;
2226   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2227     ScaledReg = 0;
2228
2229   // If folding this instruction (and it's subexprs) didn't extend any live
2230   // ranges, we're ok with it.
2231   if (BaseReg == 0 && ScaledReg == 0)
2232     return true;
2233
2234   // If all uses of this instruction are ultimately load/store/inlineasm's,
2235   // check to see if their addressing modes will include this instruction.  If
2236   // so, we can fold it into all uses, so it doesn't matter if it has multiple
2237   // uses.
2238   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2239   SmallPtrSet<Instruction*, 16> ConsideredInsts;
2240   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2241     return false;  // Has a non-memory, non-foldable use!
2242
2243   // Now that we know that all uses of this instruction are part of a chain of
2244   // computation involving only operations that could theoretically be folded
2245   // into a memory use, loop over each of these uses and see if they could
2246   // *actually* fold the instruction.
2247   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2248   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2249     Instruction *User = MemoryUses[i].first;
2250     unsigned OpNo = MemoryUses[i].second;
2251
2252     // Get the access type of this use.  If the use isn't a pointer, we don't
2253     // know what it accesses.
2254     Value *Address = User->getOperand(OpNo);
2255     if (!Address->getType()->isPointerTy())
2256       return false;
2257     Type *AddressAccessTy = Address->getType()->getPointerElementType();
2258
2259     // Do a match against the root of this address, ignoring profitability. This
2260     // will tell us if the addressing mode for the memory operation will
2261     // *actually* cover the shared instruction.
2262     ExtAddrMode Result;
2263     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2264         TPT.getRestorationPoint();
2265     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2266                                   MemoryInst, Result, InsertedTruncs,
2267                                   PromotedInsts, TPT);
2268     Matcher.IgnoreProfitability = true;
2269     bool Success = Matcher.MatchAddr(Address, 0);
2270     (void)Success; assert(Success && "Couldn't select *anything*?");
2271
2272     // The match was to check the profitability, the changes made are not
2273     // part of the original matcher. Therefore, they should be dropped
2274     // otherwise the original matcher will not present the right state.
2275     TPT.rollback(LastKnownGood);
2276
2277     // If the match didn't cover I, then it won't be shared by it.
2278     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2279                   I) == MatchedAddrModeInsts.end())
2280       return false;
2281
2282     MatchedAddrModeInsts.clear();
2283   }
2284
2285   return true;
2286 }
2287
2288 } // end anonymous namespace
2289
2290 /// IsNonLocalValue - Return true if the specified values are defined in a
2291 /// different basic block than BB.
2292 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2293   if (Instruction *I = dyn_cast<Instruction>(V))
2294     return I->getParent() != BB;
2295   return false;
2296 }
2297
2298 /// OptimizeMemoryInst - Load and Store Instructions often have
2299 /// addressing modes that can do significant amounts of computation.  As such,
2300 /// instruction selection will try to get the load or store to do as much
2301 /// computation as possible for the program.  The problem is that isel can only
2302 /// see within a single block.  As such, we sink as much legal addressing mode
2303 /// stuff into the block as possible.
2304 ///
2305 /// This method is used to optimize both load/store and inline asms with memory
2306 /// operands.
2307 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2308                                         Type *AccessTy) {
2309   Value *Repl = Addr;
2310
2311   // Try to collapse single-value PHI nodes.  This is necessary to undo
2312   // unprofitable PRE transformations.
2313   SmallVector<Value*, 8> worklist;
2314   SmallPtrSet<Value*, 16> Visited;
2315   worklist.push_back(Addr);
2316
2317   // Use a worklist to iteratively look through PHI nodes, and ensure that
2318   // the addressing mode obtained from the non-PHI roots of the graph
2319   // are equivalent.
2320   Value *Consensus = 0;
2321   unsigned NumUsesConsensus = 0;
2322   bool IsNumUsesConsensusValid = false;
2323   SmallVector<Instruction*, 16> AddrModeInsts;
2324   ExtAddrMode AddrMode;
2325   TypePromotionTransaction TPT;
2326   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2327       TPT.getRestorationPoint();
2328   while (!worklist.empty()) {
2329     Value *V = worklist.back();
2330     worklist.pop_back();
2331
2332     // Break use-def graph loops.
2333     if (!Visited.insert(V)) {
2334       Consensus = 0;
2335       break;
2336     }
2337
2338     // For a PHI node, push all of its incoming values.
2339     if (PHINode *P = dyn_cast<PHINode>(V)) {
2340       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2341         worklist.push_back(P->getIncomingValue(i));
2342       continue;
2343     }
2344
2345     // For non-PHIs, determine the addressing mode being computed.
2346     SmallVector<Instruction*, 16> NewAddrModeInsts;
2347     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2348         V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2349         PromotedInsts, TPT);
2350
2351     // This check is broken into two cases with very similar code to avoid using
2352     // getNumUses() as much as possible. Some values have a lot of uses, so
2353     // calling getNumUses() unconditionally caused a significant compile-time
2354     // regression.
2355     if (!Consensus) {
2356       Consensus = V;
2357       AddrMode = NewAddrMode;
2358       AddrModeInsts = NewAddrModeInsts;
2359       continue;
2360     } else if (NewAddrMode == AddrMode) {
2361       if (!IsNumUsesConsensusValid) {
2362         NumUsesConsensus = Consensus->getNumUses();
2363         IsNumUsesConsensusValid = true;
2364       }
2365
2366       // Ensure that the obtained addressing mode is equivalent to that obtained
2367       // for all other roots of the PHI traversal.  Also, when choosing one
2368       // such root as representative, select the one with the most uses in order
2369       // to keep the cost modeling heuristics in AddressingModeMatcher
2370       // applicable.
2371       unsigned NumUses = V->getNumUses();
2372       if (NumUses > NumUsesConsensus) {
2373         Consensus = V;
2374         NumUsesConsensus = NumUses;
2375         AddrModeInsts = NewAddrModeInsts;
2376       }
2377       continue;
2378     }
2379
2380     Consensus = 0;
2381     break;
2382   }
2383
2384   // If the addressing mode couldn't be determined, or if multiple different
2385   // ones were determined, bail out now.
2386   if (!Consensus) {
2387     TPT.rollback(LastKnownGood);
2388     return false;
2389   }
2390   TPT.commit();
2391
2392   // Check to see if any of the instructions supersumed by this addr mode are
2393   // non-local to I's BB.
2394   bool AnyNonLocal = false;
2395   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2396     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2397       AnyNonLocal = true;
2398       break;
2399     }
2400   }
2401
2402   // If all the instructions matched are already in this BB, don't do anything.
2403   if (!AnyNonLocal) {
2404     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
2405     return false;
2406   }
2407
2408   // Insert this computation right after this user.  Since our caller is
2409   // scanning from the top of the BB to the bottom, reuse of the expr are
2410   // guaranteed to happen later.
2411   IRBuilder<> Builder(MemoryInst);
2412
2413   // Now that we determined the addressing expression we want to use and know
2414   // that we have to sink it into this block.  Check to see if we have already
2415   // done this for some other load/store instr in this block.  If so, reuse the
2416   // computation.
2417   Value *&SunkAddr = SunkAddrs[Addr];
2418   if (SunkAddr) {
2419     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2420                  << *MemoryInst);
2421     if (SunkAddr->getType() != Addr->getType())
2422       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2423   } else {
2424     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2425                  << *MemoryInst);
2426     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2427     Value *Result = 0;
2428
2429     // Start with the base register. Do this first so that subsequent address
2430     // matching finds it last, which will prevent it from trying to match it
2431     // as the scaled value in case it happens to be a mul. That would be
2432     // problematic if we've sunk a different mul for the scale, because then
2433     // we'd end up sinking both muls.
2434     if (AddrMode.BaseReg) {
2435       Value *V = AddrMode.BaseReg;
2436       if (V->getType()->isPointerTy())
2437         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2438       if (V->getType() != IntPtrTy)
2439         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2440       Result = V;
2441     }
2442
2443     // Add the scale value.
2444     if (AddrMode.Scale) {
2445       Value *V = AddrMode.ScaledReg;
2446       if (V->getType() == IntPtrTy) {
2447         // done.
2448       } else if (V->getType()->isPointerTy()) {
2449         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2450       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2451                  cast<IntegerType>(V->getType())->getBitWidth()) {
2452         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2453       } else {
2454         // It is only safe to sign extend the BaseReg if we know that the math
2455         // required to create it did not overflow before we extend it. Since
2456         // the original IR value was tossed in favor of a constant back when
2457         // the AddrMode was created we need to bail out gracefully if widths
2458         // do not match instead of extending it.
2459         if (Result != AddrMode.BaseReg)
2460             cast<Instruction>(Result)->eraseFromParent();
2461         return false;
2462       }
2463       if (AddrMode.Scale != 1)
2464         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2465                               "sunkaddr");
2466       if (Result)
2467         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2468       else
2469         Result = V;
2470     }
2471
2472     // Add in the BaseGV if present.
2473     if (AddrMode.BaseGV) {
2474       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2475       if (Result)
2476         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2477       else
2478         Result = V;
2479     }
2480
2481     // Add in the Base Offset if present.
2482     if (AddrMode.BaseOffs) {
2483       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2484       if (Result)
2485         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2486       else
2487         Result = V;
2488     }
2489
2490     if (Result == 0)
2491       SunkAddr = Constant::getNullValue(Addr->getType());
2492     else
2493       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2494   }
2495
2496   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2497
2498   // If we have no uses, recursively delete the value and all dead instructions
2499   // using it.
2500   if (Repl->use_empty()) {
2501     // This can cause recursive deletion, which can invalidate our iterator.
2502     // Use a WeakVH to hold onto it in case this happens.
2503     WeakVH IterHandle(CurInstIterator);
2504     BasicBlock *BB = CurInstIterator->getParent();
2505
2506     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2507
2508     if (IterHandle != CurInstIterator) {
2509       // If the iterator instruction was recursively deleted, start over at the
2510       // start of the block.
2511       CurInstIterator = BB->begin();
2512       SunkAddrs.clear();
2513     }
2514   }
2515   ++NumMemoryInsts;
2516   return true;
2517 }
2518
2519 /// OptimizeInlineAsmInst - If there are any memory operands, use
2520 /// OptimizeMemoryInst to sink their address computing into the block when
2521 /// possible / profitable.
2522 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2523   bool MadeChange = false;
2524
2525   TargetLowering::AsmOperandInfoVector
2526     TargetConstraints = TLI->ParseConstraints(CS);
2527   unsigned ArgNo = 0;
2528   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2529     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2530
2531     // Compute the constraint code and ConstraintType to use.
2532     TLI->ComputeConstraintToUse(OpInfo, SDValue());
2533
2534     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2535         OpInfo.isIndirect) {
2536       Value *OpVal = CS->getArgOperand(ArgNo++);
2537       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2538     } else if (OpInfo.Type == InlineAsm::isInput)
2539       ArgNo++;
2540   }
2541
2542   return MadeChange;
2543 }
2544
2545 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2546 /// basic block as the load, unless conditions are unfavorable. This allows
2547 /// SelectionDAG to fold the extend into the load.
2548 ///
2549 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2550   // Look for a load being extended.
2551   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2552   if (!LI) return false;
2553
2554   // If they're already in the same block, there's nothing to do.
2555   if (LI->getParent() == I->getParent())
2556     return false;
2557
2558   // If the load has other users and the truncate is not free, this probably
2559   // isn't worthwhile.
2560   if (!LI->hasOneUse() &&
2561       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2562               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
2563       !TLI->isTruncateFree(I->getType(), LI->getType()))
2564     return false;
2565
2566   // Check whether the target supports casts folded into loads.
2567   unsigned LType;
2568   if (isa<ZExtInst>(I))
2569     LType = ISD::ZEXTLOAD;
2570   else {
2571     assert(isa<SExtInst>(I) && "Unexpected ext type!");
2572     LType = ISD::SEXTLOAD;
2573   }
2574   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
2575     return false;
2576
2577   // Move the extend into the same block as the load, so that SelectionDAG
2578   // can fold it.
2579   I->removeFromParent();
2580   I->insertAfter(LI);
2581   ++NumExtsMoved;
2582   return true;
2583 }
2584
2585 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2586   BasicBlock *DefBB = I->getParent();
2587
2588   // If the result of a {s|z}ext and its source are both live out, rewrite all
2589   // other uses of the source with result of extension.
2590   Value *Src = I->getOperand(0);
2591   if (Src->hasOneUse())
2592     return false;
2593
2594   // Only do this xform if truncating is free.
2595   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
2596     return false;
2597
2598   // Only safe to perform the optimization if the source is also defined in
2599   // this block.
2600   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
2601     return false;
2602
2603   bool DefIsLiveOut = false;
2604   for (User *U : I->users()) {
2605     Instruction *UI = cast<Instruction>(U);
2606
2607     // Figure out which BB this ext is used in.
2608     BasicBlock *UserBB = UI->getParent();
2609     if (UserBB == DefBB) continue;
2610     DefIsLiveOut = true;
2611     break;
2612   }
2613   if (!DefIsLiveOut)
2614     return false;
2615
2616   // Make sure none of the uses are PHI nodes.
2617   for (User *U : Src->users()) {
2618     Instruction *UI = cast<Instruction>(U);
2619     BasicBlock *UserBB = UI->getParent();
2620     if (UserBB == DefBB) continue;
2621     // Be conservative. We don't want this xform to end up introducing
2622     // reloads just before load / store instructions.
2623     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
2624       return false;
2625   }
2626
2627   // InsertedTruncs - Only insert one trunc in each block once.
2628   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2629
2630   bool MadeChange = false;
2631   for (Use &U : Src->uses()) {
2632     Instruction *User = cast<Instruction>(U.getUser());
2633
2634     // Figure out which BB this ext is used in.
2635     BasicBlock *UserBB = User->getParent();
2636     if (UserBB == DefBB) continue;
2637
2638     // Both src and def are live in this block. Rewrite the use.
2639     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2640
2641     if (!InsertedTrunc) {
2642       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2643       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
2644       InsertedTruncsSet.insert(InsertedTrunc);
2645     }
2646
2647     // Replace a use of the {s|z}ext source with a use of the result.
2648     U = InsertedTrunc;
2649     ++NumExtUses;
2650     MadeChange = true;
2651   }
2652
2653   return MadeChange;
2654 }
2655
2656 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2657 /// turned into an explicit branch.
2658 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2659   // FIXME: This should use the same heuristics as IfConversion to determine
2660   // whether a select is better represented as a branch.  This requires that
2661   // branch probability metadata is preserved for the select, which is not the
2662   // case currently.
2663
2664   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2665
2666   // If the branch is predicted right, an out of order CPU can avoid blocking on
2667   // the compare.  Emit cmovs on compares with a memory operand as branches to
2668   // avoid stalls on the load from memory.  If the compare has more than one use
2669   // there's probably another cmov or setcc around so it's not worth emitting a
2670   // branch.
2671   if (!Cmp)
2672     return false;
2673
2674   Value *CmpOp0 = Cmp->getOperand(0);
2675   Value *CmpOp1 = Cmp->getOperand(1);
2676
2677   // We check that the memory operand has one use to avoid uses of the loaded
2678   // value directly after the compare, making branches unprofitable.
2679   return Cmp->hasOneUse() &&
2680          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2681           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2682 }
2683
2684
2685 /// If we have a SelectInst that will likely profit from branch prediction,
2686 /// turn it into a branch.
2687 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
2688   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2689
2690   // Can we convert the 'select' to CF ?
2691   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
2692     return false;
2693
2694   TargetLowering::SelectSupportKind SelectKind;
2695   if (VectorCond)
2696     SelectKind = TargetLowering::VectorMaskSelect;
2697   else if (SI->getType()->isVectorTy())
2698     SelectKind = TargetLowering::ScalarCondVectorVal;
2699   else
2700     SelectKind = TargetLowering::ScalarValSelect;
2701
2702   // Do we have efficient codegen support for this kind of 'selects' ?
2703   if (TLI->isSelectSupported(SelectKind)) {
2704     // We have efficient codegen support for the select instruction.
2705     // Check if it is profitable to keep this 'select'.
2706     if (!TLI->isPredictableSelectExpensive() ||
2707         !isFormingBranchFromSelectProfitable(SI))
2708       return false;
2709   }
2710
2711   ModifiedDT = true;
2712
2713   // First, we split the block containing the select into 2 blocks.
2714   BasicBlock *StartBlock = SI->getParent();
2715   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2716   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2717
2718   // Create a new block serving as the landing pad for the branch.
2719   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2720                                              NextBlock->getParent(), NextBlock);
2721
2722   // Move the unconditional branch from the block with the select in it into our
2723   // landing pad block.
2724   StartBlock->getTerminator()->eraseFromParent();
2725   BranchInst::Create(NextBlock, SmallBlock);
2726
2727   // Insert the real conditional branch based on the original condition.
2728   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2729
2730   // The select itself is replaced with a PHI Node.
2731   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2732   PN->takeName(SI);
2733   PN->addIncoming(SI->getTrueValue(), StartBlock);
2734   PN->addIncoming(SI->getFalseValue(), SmallBlock);
2735   SI->replaceAllUsesWith(PN);
2736   SI->eraseFromParent();
2737
2738   // Instruct OptimizeBlock to skip to the next block.
2739   CurInstIterator = StartBlock->end();
2740   ++NumSelectsExpanded;
2741   return true;
2742 }
2743
2744 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
2745   SmallVector<int, 16> Mask(SVI->getShuffleMask());
2746   int SplatElem = -1;
2747   for (unsigned i = 0; i < Mask.size(); ++i) {
2748     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
2749       return false;
2750     SplatElem = Mask[i];
2751   }
2752
2753   return true;
2754 }
2755
2756 /// Some targets have expensive vector shifts if the lanes aren't all the same
2757 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
2758 /// it's often worth sinking a shufflevector splat down to its use so that
2759 /// codegen can spot all lanes are identical.
2760 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
2761   BasicBlock *DefBB = SVI->getParent();
2762
2763   // Only do this xform if variable vector shifts are particularly expensive.
2764   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
2765     return false;
2766
2767   // We only expect better codegen by sinking a shuffle if we can recognise a
2768   // constant splat.
2769   if (!isBroadcastShuffle(SVI))
2770     return false;
2771
2772   // InsertedShuffles - Only insert a shuffle in each block once.
2773   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
2774
2775   bool MadeChange = false;
2776   for (User *U : SVI->users()) {
2777     Instruction *UI = cast<Instruction>(U);
2778
2779     // Figure out which BB this ext is used in.
2780     BasicBlock *UserBB = UI->getParent();
2781     if (UserBB == DefBB) continue;
2782
2783     // For now only apply this when the splat is used by a shift instruction.
2784     if (!UI->isShift()) continue;
2785
2786     // Everything checks out, sink the shuffle if the user's block doesn't
2787     // already have a copy.
2788     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
2789
2790     if (!InsertedShuffle) {
2791       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2792       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
2793                                               SVI->getOperand(1),
2794                                               SVI->getOperand(2), "", InsertPt);
2795     }
2796
2797     UI->replaceUsesOfWith(SVI, InsertedShuffle);
2798     MadeChange = true;
2799   }
2800
2801   // If we removed all uses, nuke the shuffle.
2802   if (SVI->use_empty()) {
2803     SVI->eraseFromParent();
2804     MadeChange = true;
2805   }
2806
2807   return MadeChange;
2808 }
2809
2810 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
2811   if (PHINode *P = dyn_cast<PHINode>(I)) {
2812     // It is possible for very late stage optimizations (such as SimplifyCFG)
2813     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
2814     // trivial PHI, go ahead and zap it here.
2815     if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
2816                                        TLInfo, DT)) {
2817       P->replaceAllUsesWith(V);
2818       P->eraseFromParent();
2819       ++NumPHIsElim;
2820       return true;
2821     }
2822     return false;
2823   }
2824
2825   if (CastInst *CI = dyn_cast<CastInst>(I)) {
2826     // If the source of the cast is a constant, then this should have
2827     // already been constant folded.  The only reason NOT to constant fold
2828     // it is if something (e.g. LSR) was careful to place the constant
2829     // evaluation in a block other than then one that uses it (e.g. to hoist
2830     // the address of globals out of a loop).  If this is the case, we don't
2831     // want to forward-subst the cast.
2832     if (isa<Constant>(CI->getOperand(0)))
2833       return false;
2834
2835     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2836       return true;
2837
2838     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
2839       /// Sink a zext or sext into its user blocks if the target type doesn't
2840       /// fit in one register
2841       if (TLI && TLI->getTypeAction(CI->getContext(),
2842                                     TLI->getValueType(CI->getType())) ==
2843                      TargetLowering::TypeExpandInteger) {
2844         return SinkCast(CI);
2845       } else {
2846         bool MadeChange = MoveExtToFormExtLoad(I);
2847         return MadeChange | OptimizeExtUses(I);
2848       }
2849     }
2850     return false;
2851   }
2852
2853   if (CmpInst *CI = dyn_cast<CmpInst>(I))
2854     if (!TLI || !TLI->hasMultipleConditionRegisters())
2855       return OptimizeCmpExpression(CI);
2856
2857   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2858     if (TLI)
2859       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2860     return false;
2861   }
2862
2863   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
2864     if (TLI)
2865       return OptimizeMemoryInst(I, SI->getOperand(1),
2866                                 SI->getOperand(0)->getType());
2867     return false;
2868   }
2869
2870   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2871     if (GEPI->hasAllZeroIndices()) {
2872       /// The GEP operand must be a pointer, so must its result -> BitCast
2873       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
2874                                         GEPI->getName(), GEPI);
2875       GEPI->replaceAllUsesWith(NC);
2876       GEPI->eraseFromParent();
2877       ++NumGEPsElim;
2878       OptimizeInst(NC);
2879       return true;
2880     }
2881     return false;
2882   }
2883
2884   if (CallInst *CI = dyn_cast<CallInst>(I))
2885     return OptimizeCallInst(CI);
2886
2887   if (SelectInst *SI = dyn_cast<SelectInst>(I))
2888     return OptimizeSelectInst(SI);
2889
2890   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
2891     return OptimizeShuffleVectorInst(SVI);
2892
2893   return false;
2894 }
2895
2896 // In this pass we look for GEP and cast instructions that are used
2897 // across basic blocks and rewrite them to improve basic-block-at-a-time
2898 // selection.
2899 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
2900   SunkAddrs.clear();
2901   bool MadeChange = false;
2902
2903   CurInstIterator = BB.begin();
2904   while (CurInstIterator != BB.end())
2905     MadeChange |= OptimizeInst(CurInstIterator++);
2906
2907   MadeChange |= DupRetToEnableTailCallOpts(&BB);
2908
2909   return MadeChange;
2910 }
2911
2912 // llvm.dbg.value is far away from the value then iSel may not be able
2913 // handle it properly. iSel will drop llvm.dbg.value if it can not
2914 // find a node corresponding to the value.
2915 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
2916   bool MadeChange = false;
2917   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2918     Instruction *PrevNonDbgInst = NULL;
2919     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
2920       Instruction *Insn = BI; ++BI;
2921       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
2922       if (!DVI) {
2923         PrevNonDbgInst = Insn;
2924         continue;
2925       }
2926
2927       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
2928       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
2929         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
2930         DVI->removeFromParent();
2931         if (isa<PHINode>(VI))
2932           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
2933         else
2934           DVI->insertAfter(VI);
2935         MadeChange = true;
2936         ++NumDbgValueMoved;
2937       }
2938     }
2939   }
2940   return MadeChange;
2941 }
2942
2943 // If there is a sequence that branches based on comparing a single bit
2944 // against zero that can be combined into a single instruction, and the
2945 // target supports folding these into a single instruction, sink the
2946 // mask and compare into the branch uses. Do this before OptimizeBlock ->
2947 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
2948 // searched for.
2949 bool CodeGenPrepare::sinkAndCmp(Function &F) {
2950   if (!EnableAndCmpSinking)
2951     return false;
2952   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
2953     return false;
2954   bool MadeChange = false;
2955   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
2956     BasicBlock *BB = I++;
2957
2958     // Does this BB end with the following?
2959     //   %andVal = and %val, #single-bit-set
2960     //   %icmpVal = icmp %andResult, 0
2961     //   br i1 %cmpVal label %dest1, label %dest2"
2962     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
2963     if (!Brcc || !Brcc->isConditional())
2964       continue;
2965     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
2966     if (!Cmp || Cmp->getParent() != BB)
2967       continue;
2968     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
2969     if (!Zero || !Zero->isZero())
2970       continue;
2971     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
2972     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
2973       continue;
2974     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
2975     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
2976       continue;
2977     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
2978
2979     // Push the "and; icmp" for any users that are conditional branches.
2980     // Since there can only be one branch use per BB, we don't need to keep
2981     // track of which BBs we insert into.
2982     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
2983          UI != E; ) {
2984       Use &TheUse = *UI;
2985       // Find brcc use.
2986       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
2987       ++UI;
2988       if (!BrccUser || !BrccUser->isConditional())
2989         continue;
2990       BasicBlock *UserBB = BrccUser->getParent();
2991       if (UserBB == BB) continue;
2992       DEBUG(dbgs() << "found Brcc use\n");
2993
2994       // Sink the "and; icmp" to use.
2995       MadeChange = true;
2996       BinaryOperator *NewAnd =
2997         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
2998                                   BrccUser);
2999       CmpInst *NewCmp =
3000         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3001                         "", BrccUser);
3002       TheUse = NewCmp;
3003       ++NumAndCmpsMoved;
3004       DEBUG(BrccUser->getParent()->dump());
3005     }
3006   }
3007   return MadeChange;
3008 }