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