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