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