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