577c048ba60e20bae23efb98c88bee68fb828a27
[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 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/TargetTransformInfo.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/MDBuilder.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/ValueHandle.h"
36 #include "llvm/IR/ValueMap.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/BuildLibCalls.h"
46 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 using namespace llvm;
49 using namespace llvm::PatternMatch;
50
51 #define DEBUG_TYPE "codegenprepare"
52
53 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
54 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
55 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
56 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
57                       "sunken Cmps");
58 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
59                        "of sunken Casts");
60 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
61                           "computations were sunk");
62 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
63 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
64 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
65 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
66 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
67 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
68 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
69
70 static cl::opt<bool> DisableBranchOpts(
71   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
72   cl::desc("Disable branch optimizations in CodeGenPrepare"));
73
74 static cl::opt<bool> DisableSelectToBranch(
75   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76   cl::desc("Disable select to branch conversion."));
77
78 static cl::opt<bool> AddrSinkUsingGEPs(
79   "addr-sink-using-gep", cl::Hidden, cl::init(false),
80   cl::desc("Address sinking in CGP using GEPs."));
81
82 static cl::opt<bool> EnableAndCmpSinking(
83    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
84    cl::desc("Enable sinkinig and/cmp into branches."));
85
86 static cl::opt<bool> DisableStoreExtract(
87     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
88     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
89
90 static cl::opt<bool> StressStoreExtract(
91     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
92     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
93
94 namespace {
95 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
96 struct TypeIsSExt {
97   Type *Ty;
98   bool IsSExt;
99   TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
100 };
101 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
102
103   class CodeGenPrepare : public FunctionPass {
104     /// TLI - Keep a pointer of a TargetLowering to consult for determining
105     /// transformation profitability.
106     const TargetMachine *TM;
107     const TargetLowering *TLI;
108     const TargetTransformInfo *TTI;
109     const TargetLibraryInfo *TLInfo;
110     DominatorTree *DT;
111
112     /// CurInstIterator - As we scan instructions optimizing them, this is the
113     /// next instruction to optimize.  Xforms that can invalidate this should
114     /// update it.
115     BasicBlock::iterator CurInstIterator;
116
117     /// Keeps track of non-local addresses that have been sunk into a block.
118     /// This allows us to avoid inserting duplicate code for blocks with
119     /// multiple load/stores of the same address.
120     ValueMap<Value*, Value*> SunkAddrs;
121
122     /// Keeps track of all truncates inserted for the current function.
123     SetOfInstrs InsertedTruncsSet;
124     /// Keeps track of the type of the related instruction before their
125     /// promotion for the current function.
126     InstrToOrigTy PromotedInsts;
127
128     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
129     /// be updated.
130     bool ModifiedDT;
131
132     /// OptSize - True if optimizing for size.
133     bool OptSize;
134
135   public:
136     static char ID; // Pass identification, replacement for typeid
137     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
138         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
139         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
140       }
141     bool runOnFunction(Function &F) override;
142
143     const char *getPassName() const override { return "CodeGen Prepare"; }
144
145     void getAnalysisUsage(AnalysisUsage &AU) const override {
146       AU.addPreserved<DominatorTreeWrapperPass>();
147       AU.addRequired<TargetLibraryInfo>();
148       AU.addRequired<TargetTransformInfo>();
149     }
150
151   private:
152     bool EliminateFallThrough(Function &F);
153     bool EliminateMostlyEmptyBlocks(Function &F);
154     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
155     void EliminateMostlyEmptyBlock(BasicBlock *BB);
156     bool OptimizeBlock(BasicBlock &BB);
157     bool OptimizeInst(Instruction *I);
158     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
159     bool OptimizeInlineAsmInst(CallInst *CS);
160     bool OptimizeCallInst(CallInst *CI);
161     bool MoveExtToFormExtLoad(Instruction *I);
162     bool OptimizeExtUses(Instruction *I);
163     bool OptimizeSelectInst(SelectInst *SI);
164     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
165     bool OptimizeExtractElementInst(Instruction *Inst);
166     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
167     bool PlaceDbgValues(Function &F);
168     bool sinkAndCmp(Function &F);
169     bool splitBranchCondition(Function &F);
170   };
171 }
172
173 char CodeGenPrepare::ID = 0;
174 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
175                    "Optimize for code generation", false, false)
176
177 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
178   return new CodeGenPrepare(TM);
179 }
180
181 bool CodeGenPrepare::runOnFunction(Function &F) {
182   if (skipOptnoneFunction(F))
183     return false;
184
185   bool EverMadeChange = false;
186   // Clear per function information.
187   InsertedTruncsSet.clear();
188   PromotedInsts.clear();
189
190   ModifiedDT = false;
191   if (TM)
192     TLI = TM->getSubtargetImpl()->getTargetLowering();
193   TLInfo = &getAnalysis<TargetLibraryInfo>();
194   TTI = &getAnalysis<TargetTransformInfo>();
195   DominatorTreeWrapperPass *DTWP =
196       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
197   DT = DTWP ? &DTWP->getDomTree() : nullptr;
198   OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
199                                            Attribute::OptimizeForSize);
200
201   /// This optimization identifies DIV instructions that can be
202   /// profitably bypassed and carried out with a shorter, faster divide.
203   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
204     const DenseMap<unsigned int, unsigned int> &BypassWidths =
205        TLI->getBypassSlowDivWidths();
206     for (Function::iterator I = F.begin(); I != F.end(); I++)
207       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
208   }
209
210   // Eliminate blocks that contain only PHI nodes and an
211   // unconditional branch.
212   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
213
214   // llvm.dbg.value is far away from the value then iSel may not be able
215   // handle it properly. iSel will drop llvm.dbg.value if it can not
216   // find a node corresponding to the value.
217   EverMadeChange |= PlaceDbgValues(F);
218
219   // If there is a mask, compare against zero, and branch that can be combined
220   // into a single target instruction, push the mask and compare into branch
221   // users. Do this before OptimizeBlock -> OptimizeInst ->
222   // OptimizeCmpExpression, which perturbs the pattern being searched for.
223   if (!DisableBranchOpts) {
224     EverMadeChange |= sinkAndCmp(F);
225     EverMadeChange |= splitBranchCondition(F);
226   }
227
228   bool MadeChange = true;
229   while (MadeChange) {
230     MadeChange = false;
231     for (Function::iterator I = F.begin(); I != F.end(); ) {
232       BasicBlock *BB = I++;
233       MadeChange |= OptimizeBlock(*BB);
234     }
235     EverMadeChange |= MadeChange;
236   }
237
238   SunkAddrs.clear();
239
240   if (!DisableBranchOpts) {
241     MadeChange = false;
242     SmallPtrSet<BasicBlock*, 8> WorkList;
243     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
244       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
245       MadeChange |= ConstantFoldTerminator(BB, true);
246       if (!MadeChange) continue;
247
248       for (SmallVectorImpl<BasicBlock*>::iterator
249              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
250         if (pred_begin(*II) == pred_end(*II))
251           WorkList.insert(*II);
252     }
253
254     // Delete the dead blocks and any of their dead successors.
255     MadeChange |= !WorkList.empty();
256     while (!WorkList.empty()) {
257       BasicBlock *BB = *WorkList.begin();
258       WorkList.erase(BB);
259       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
260
261       DeleteDeadBlock(BB);
262
263       for (SmallVectorImpl<BasicBlock*>::iterator
264              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
265         if (pred_begin(*II) == pred_end(*II))
266           WorkList.insert(*II);
267     }
268
269     // Merge pairs of basic blocks with unconditional branches, connected by
270     // a single edge.
271     if (EverMadeChange || MadeChange)
272       MadeChange |= EliminateFallThrough(F);
273
274     if (MadeChange)
275       ModifiedDT = true;
276     EverMadeChange |= MadeChange;
277   }
278
279   if (ModifiedDT && DT)
280     DT->recalculate(F);
281
282   return EverMadeChange;
283 }
284
285 /// EliminateFallThrough - Merge basic blocks which are connected
286 /// by a single edge, where one of the basic blocks has a single successor
287 /// pointing to the other basic block, which has a single predecessor.
288 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
289   bool Changed = false;
290   // Scan all of the blocks in the function, except for the entry block.
291   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
292     BasicBlock *BB = I++;
293     // If the destination block has a single pred, then this is a trivial
294     // edge, just collapse it.
295     BasicBlock *SinglePred = BB->getSinglePredecessor();
296
297     // Don't merge if BB's address is taken.
298     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
299
300     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
301     if (Term && !Term->isConditional()) {
302       Changed = true;
303       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
304       // Remember if SinglePred was the entry block of the function.
305       // If so, we will need to move BB back to the entry position.
306       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
307       MergeBasicBlockIntoOnlyPred(BB, this);
308
309       if (isEntry && BB != &BB->getParent()->getEntryBlock())
310         BB->moveBefore(&BB->getParent()->getEntryBlock());
311
312       // We have erased a block. Update the iterator.
313       I = BB;
314     }
315   }
316   return Changed;
317 }
318
319 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
320 /// debug info directives, and an unconditional branch.  Passes before isel
321 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
322 /// isel.  Start by eliminating these blocks so we can split them the way we
323 /// want them.
324 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
325   bool MadeChange = false;
326   // Note that this intentionally skips the entry block.
327   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
328     BasicBlock *BB = I++;
329
330     // If this block doesn't end with an uncond branch, ignore it.
331     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
332     if (!BI || !BI->isUnconditional())
333       continue;
334
335     // If the instruction before the branch (skipping debug info) isn't a phi
336     // node, then other stuff is happening here.
337     BasicBlock::iterator BBI = BI;
338     if (BBI != BB->begin()) {
339       --BBI;
340       while (isa<DbgInfoIntrinsic>(BBI)) {
341         if (BBI == BB->begin())
342           break;
343         --BBI;
344       }
345       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
346         continue;
347     }
348
349     // Do not break infinite loops.
350     BasicBlock *DestBB = BI->getSuccessor(0);
351     if (DestBB == BB)
352       continue;
353
354     if (!CanMergeBlocks(BB, DestBB))
355       continue;
356
357     EliminateMostlyEmptyBlock(BB);
358     MadeChange = true;
359   }
360   return MadeChange;
361 }
362
363 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
364 /// single uncond branch between them, and BB contains no other non-phi
365 /// instructions.
366 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
367                                     const BasicBlock *DestBB) const {
368   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
369   // the successor.  If there are more complex condition (e.g. preheaders),
370   // don't mess around with them.
371   BasicBlock::const_iterator BBI = BB->begin();
372   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
373     for (const User *U : PN->users()) {
374       const Instruction *UI = cast<Instruction>(U);
375       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
376         return false;
377       // If User is inside DestBB block and it is a PHINode then check
378       // incoming value. If incoming value is not from BB then this is
379       // a complex condition (e.g. preheaders) we want to avoid here.
380       if (UI->getParent() == DestBB) {
381         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
382           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
383             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
384             if (Insn && Insn->getParent() == BB &&
385                 Insn->getParent() != UPN->getIncomingBlock(I))
386               return false;
387           }
388       }
389     }
390   }
391
392   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
393   // and DestBB may have conflicting incoming values for the block.  If so, we
394   // can't merge the block.
395   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
396   if (!DestBBPN) return true;  // no conflict.
397
398   // Collect the preds of BB.
399   SmallPtrSet<const BasicBlock*, 16> BBPreds;
400   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
401     // It is faster to get preds from a PHI than with pred_iterator.
402     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
403       BBPreds.insert(BBPN->getIncomingBlock(i));
404   } else {
405     BBPreds.insert(pred_begin(BB), pred_end(BB));
406   }
407
408   // Walk the preds of DestBB.
409   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
410     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
411     if (BBPreds.count(Pred)) {   // Common predecessor?
412       BBI = DestBB->begin();
413       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
414         const Value *V1 = PN->getIncomingValueForBlock(Pred);
415         const Value *V2 = PN->getIncomingValueForBlock(BB);
416
417         // If V2 is a phi node in BB, look up what the mapped value will be.
418         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
419           if (V2PN->getParent() == BB)
420             V2 = V2PN->getIncomingValueForBlock(Pred);
421
422         // If there is a conflict, bail out.
423         if (V1 != V2) return false;
424       }
425     }
426   }
427
428   return true;
429 }
430
431
432 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
433 /// an unconditional branch in it.
434 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
435   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
436   BasicBlock *DestBB = BI->getSuccessor(0);
437
438   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
439
440   // If the destination block has a single pred, then this is a trivial edge,
441   // just collapse it.
442   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
443     if (SinglePred != DestBB) {
444       // Remember if SinglePred was the entry block of the function.  If so, we
445       // will need to move BB back to the entry position.
446       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
447       MergeBasicBlockIntoOnlyPred(DestBB, this);
448
449       if (isEntry && BB != &BB->getParent()->getEntryBlock())
450         BB->moveBefore(&BB->getParent()->getEntryBlock());
451
452       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
453       return;
454     }
455   }
456
457   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
458   // to handle the new incoming edges it is about to have.
459   PHINode *PN;
460   for (BasicBlock::iterator BBI = DestBB->begin();
461        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
462     // Remove the incoming value for BB, and remember it.
463     Value *InVal = PN->removeIncomingValue(BB, false);
464
465     // Two options: either the InVal is a phi node defined in BB or it is some
466     // value that dominates BB.
467     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
468     if (InValPhi && InValPhi->getParent() == BB) {
469       // Add all of the input values of the input PHI as inputs of this phi.
470       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
471         PN->addIncoming(InValPhi->getIncomingValue(i),
472                         InValPhi->getIncomingBlock(i));
473     } else {
474       // Otherwise, add one instance of the dominating value for each edge that
475       // we will be adding.
476       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
477         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
478           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
479       } else {
480         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
481           PN->addIncoming(InVal, *PI);
482       }
483     }
484   }
485
486   // The PHIs are now updated, change everything that refers to BB to use
487   // DestBB and remove BB.
488   BB->replaceAllUsesWith(DestBB);
489   if (DT && !ModifiedDT) {
490     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
491     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
492     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
493     DT->changeImmediateDominator(DestBB, NewIDom);
494     DT->eraseNode(BB);
495   }
496   BB->eraseFromParent();
497   ++NumBlocksElim;
498
499   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
500 }
501
502 /// SinkCast - Sink the specified cast instruction into its user blocks
503 static bool SinkCast(CastInst *CI) {
504   BasicBlock *DefBB = CI->getParent();
505
506   /// InsertedCasts - Only insert a cast in each block once.
507   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
508
509   bool MadeChange = false;
510   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
511        UI != E; ) {
512     Use &TheUse = UI.getUse();
513     Instruction *User = cast<Instruction>(*UI);
514
515     // Figure out which BB this cast is used in.  For PHI's this is the
516     // appropriate predecessor block.
517     BasicBlock *UserBB = User->getParent();
518     if (PHINode *PN = dyn_cast<PHINode>(User)) {
519       UserBB = PN->getIncomingBlock(TheUse);
520     }
521
522     // Preincrement use iterator so we don't invalidate it.
523     ++UI;
524
525     // If this user is in the same block as the cast, don't change the cast.
526     if (UserBB == DefBB) continue;
527
528     // If we have already inserted a cast into this block, use it.
529     CastInst *&InsertedCast = InsertedCasts[UserBB];
530
531     if (!InsertedCast) {
532       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
533       InsertedCast =
534         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
535                          InsertPt);
536       MadeChange = true;
537     }
538
539     // Replace a use of the cast with a use of the new cast.
540     TheUse = InsertedCast;
541     ++NumCastUses;
542   }
543
544   // If we removed all uses, nuke the cast.
545   if (CI->use_empty()) {
546     CI->eraseFromParent();
547     MadeChange = true;
548   }
549
550   return MadeChange;
551 }
552
553 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
554 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
555 /// sink it into user blocks to reduce the number of virtual
556 /// registers that must be created and coalesced.
557 ///
558 /// Return true if any changes are made.
559 ///
560 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
561   // If this is a noop copy,
562   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
563   EVT DstVT = TLI.getValueType(CI->getType());
564
565   // This is an fp<->int conversion?
566   if (SrcVT.isInteger() != DstVT.isInteger())
567     return false;
568
569   // If this is an extension, it will be a zero or sign extension, which
570   // isn't a noop.
571   if (SrcVT.bitsLT(DstVT)) return false;
572
573   // If these values will be promoted, find out what they will be promoted
574   // to.  This helps us consider truncates on PPC as noop copies when they
575   // are.
576   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
577       TargetLowering::TypePromoteInteger)
578     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
579   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
580       TargetLowering::TypePromoteInteger)
581     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
582
583   // If, after promotion, these are the same types, this is a noop copy.
584   if (SrcVT != DstVT)
585     return false;
586
587   return SinkCast(CI);
588 }
589
590 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
591 /// the number of virtual registers that must be created and coalesced.  This is
592 /// a clear win except on targets with multiple condition code registers
593 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
594 ///
595 /// Return true if any changes are made.
596 static bool OptimizeCmpExpression(CmpInst *CI) {
597   BasicBlock *DefBB = CI->getParent();
598
599   /// InsertedCmp - Only insert a cmp in each block once.
600   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
601
602   bool MadeChange = false;
603   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
604        UI != E; ) {
605     Use &TheUse = UI.getUse();
606     Instruction *User = cast<Instruction>(*UI);
607
608     // Preincrement use iterator so we don't invalidate it.
609     ++UI;
610
611     // Don't bother for PHI nodes.
612     if (isa<PHINode>(User))
613       continue;
614
615     // Figure out which BB this cmp is used in.
616     BasicBlock *UserBB = User->getParent();
617
618     // If this user is in the same block as the cmp, don't change the cmp.
619     if (UserBB == DefBB) continue;
620
621     // If we have already inserted a cmp into this block, use it.
622     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
623
624     if (!InsertedCmp) {
625       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
626       InsertedCmp =
627         CmpInst::Create(CI->getOpcode(),
628                         CI->getPredicate(),  CI->getOperand(0),
629                         CI->getOperand(1), "", InsertPt);
630       MadeChange = true;
631     }
632
633     // Replace a use of the cmp with a use of the new cmp.
634     TheUse = InsertedCmp;
635     ++NumCmpUses;
636   }
637
638   // If we removed all uses, nuke the cmp.
639   if (CI->use_empty())
640     CI->eraseFromParent();
641
642   return MadeChange;
643 }
644
645 /// isExtractBitsCandidateUse - Check if the candidates could
646 /// be combined with shift instruction, which includes:
647 /// 1. Truncate instruction
648 /// 2. And instruction and the imm is a mask of the low bits:
649 /// imm & (imm+1) == 0
650 static bool isExtractBitsCandidateUse(Instruction *User) {
651   if (!isa<TruncInst>(User)) {
652     if (User->getOpcode() != Instruction::And ||
653         !isa<ConstantInt>(User->getOperand(1)))
654       return false;
655
656     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
657
658     if ((Cimm & (Cimm + 1)).getBoolValue())
659       return false;
660   }
661   return true;
662 }
663
664 /// SinkShiftAndTruncate - sink both shift and truncate instruction
665 /// to the use of truncate's BB.
666 static bool
667 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
668                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
669                      const TargetLowering &TLI) {
670   BasicBlock *UserBB = User->getParent();
671   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
672   TruncInst *TruncI = dyn_cast<TruncInst>(User);
673   bool MadeChange = false;
674
675   for (Value::user_iterator TruncUI = TruncI->user_begin(),
676                             TruncE = TruncI->user_end();
677        TruncUI != TruncE;) {
678
679     Use &TruncTheUse = TruncUI.getUse();
680     Instruction *TruncUser = cast<Instruction>(*TruncUI);
681     // Preincrement use iterator so we don't invalidate it.
682
683     ++TruncUI;
684
685     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
686     if (!ISDOpcode)
687       continue;
688
689     // If the use is actually a legal node, there will not be an
690     // implicit truncate.
691     // FIXME: always querying the result type is just an
692     // approximation; some nodes' legality is determined by the
693     // operand or other means. There's no good way to find out though.
694     if (TLI.isOperationLegalOrCustom(
695             ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
696       continue;
697
698     // Don't bother for PHI nodes.
699     if (isa<PHINode>(TruncUser))
700       continue;
701
702     BasicBlock *TruncUserBB = TruncUser->getParent();
703
704     if (UserBB == TruncUserBB)
705       continue;
706
707     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
708     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
709
710     if (!InsertedShift && !InsertedTrunc) {
711       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
712       // Sink the shift
713       if (ShiftI->getOpcode() == Instruction::AShr)
714         InsertedShift =
715             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
716       else
717         InsertedShift =
718             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
719
720       // Sink the trunc
721       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
722       TruncInsertPt++;
723
724       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
725                                        TruncI->getType(), "", TruncInsertPt);
726
727       MadeChange = true;
728
729       TruncTheUse = InsertedTrunc;
730     }
731   }
732   return MadeChange;
733 }
734
735 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
736 /// the uses could potentially be combined with this shift instruction and
737 /// generate BitExtract instruction. It will only be applied if the architecture
738 /// supports BitExtract instruction. Here is an example:
739 /// BB1:
740 ///   %x.extract.shift = lshr i64 %arg1, 32
741 /// BB2:
742 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
743 /// ==>
744 ///
745 /// BB2:
746 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
747 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
748 ///
749 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
750 /// instruction.
751 /// Return true if any changes are made.
752 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
753                                 const TargetLowering &TLI) {
754   BasicBlock *DefBB = ShiftI->getParent();
755
756   /// Only insert instructions in each block once.
757   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
758
759   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
760
761   bool MadeChange = false;
762   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
763        UI != E;) {
764     Use &TheUse = UI.getUse();
765     Instruction *User = cast<Instruction>(*UI);
766     // Preincrement use iterator so we don't invalidate it.
767     ++UI;
768
769     // Don't bother for PHI nodes.
770     if (isa<PHINode>(User))
771       continue;
772
773     if (!isExtractBitsCandidateUse(User))
774       continue;
775
776     BasicBlock *UserBB = User->getParent();
777
778     if (UserBB == DefBB) {
779       // If the shift and truncate instruction are in the same BB. The use of
780       // the truncate(TruncUse) may still introduce another truncate if not
781       // legal. In this case, we would like to sink both shift and truncate
782       // instruction to the BB of TruncUse.
783       // for example:
784       // BB1:
785       // i64 shift.result = lshr i64 opnd, imm
786       // trunc.result = trunc shift.result to i16
787       //
788       // BB2:
789       //   ----> We will have an implicit truncate here if the architecture does
790       //   not have i16 compare.
791       // cmp i16 trunc.result, opnd2
792       //
793       if (isa<TruncInst>(User) && shiftIsLegal
794           // If the type of the truncate is legal, no trucate will be
795           // introduced in other basic blocks.
796           && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
797         MadeChange =
798             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
799
800       continue;
801     }
802     // If we have already inserted a shift into this block, use it.
803     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
804
805     if (!InsertedShift) {
806       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
807
808       if (ShiftI->getOpcode() == Instruction::AShr)
809         InsertedShift =
810             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
811       else
812         InsertedShift =
813             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
814
815       MadeChange = true;
816     }
817
818     // Replace a use of the shift with a use of the new shift.
819     TheUse = InsertedShift;
820   }
821
822   // If we removed all uses, nuke the shift.
823   if (ShiftI->use_empty())
824     ShiftI->eraseFromParent();
825
826   return MadeChange;
827 }
828
829 namespace {
830 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
831 protected:
832   void replaceCall(Value *With) override {
833     CI->replaceAllUsesWith(With);
834     CI->eraseFromParent();
835   }
836   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
837       if (ConstantInt *SizeCI =
838                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
839         return SizeCI->isAllOnesValue();
840     return false;
841   }
842 };
843 } // end anonymous namespace
844
845 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
846   BasicBlock *BB = CI->getParent();
847
848   // Lower inline assembly if we can.
849   // If we found an inline asm expession, and if the target knows how to
850   // lower it to normal LLVM code, do so now.
851   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
852     if (TLI->ExpandInlineAsm(CI)) {
853       // Avoid invalidating the iterator.
854       CurInstIterator = BB->begin();
855       // Avoid processing instructions out of order, which could cause
856       // reuse before a value is defined.
857       SunkAddrs.clear();
858       return true;
859     }
860     // Sink address computing for memory operands into the block.
861     if (OptimizeInlineAsmInst(CI))
862       return true;
863   }
864
865   // Lower all uses of llvm.objectsize.*
866   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
867   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
868     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
869     Type *ReturnTy = CI->getType();
870     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
871
872     // Substituting this can cause recursive simplifications, which can
873     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
874     // happens.
875     WeakVH IterHandle(CurInstIterator);
876
877     replaceAndRecursivelySimplify(CI, RetVal,
878                                   TLI ? TLI->getDataLayout() : nullptr,
879                                   TLInfo, ModifiedDT ? nullptr : DT);
880
881     // If the iterator instruction was recursively deleted, start over at the
882     // start of the block.
883     if (IterHandle != CurInstIterator) {
884       CurInstIterator = BB->begin();
885       SunkAddrs.clear();
886     }
887     return true;
888   }
889
890   if (II && TLI) {
891     SmallVector<Value*, 2> PtrOps;
892     Type *AccessTy;
893     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
894       while (!PtrOps.empty())
895         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
896           return true;
897   }
898
899   // From here on out we're working with named functions.
900   if (!CI->getCalledFunction()) return false;
901
902   // We'll need DataLayout from here on out.
903   const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
904   if (!TD) return false;
905
906   // Lower all default uses of _chk calls.  This is very similar
907   // to what InstCombineCalls does, but here we are only lowering calls
908   // that have the default "don't know" as the objectsize.  Anything else
909   // should be left alone.
910   CodeGenPrepareFortifiedLibCalls Simplifier;
911   return Simplifier.fold(CI, TD, TLInfo);
912 }
913
914 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
915 /// instructions to the predecessor to enable tail call optimizations. The
916 /// case it is currently looking for is:
917 /// @code
918 /// bb0:
919 ///   %tmp0 = tail call i32 @f0()
920 ///   br label %return
921 /// bb1:
922 ///   %tmp1 = tail call i32 @f1()
923 ///   br label %return
924 /// bb2:
925 ///   %tmp2 = tail call i32 @f2()
926 ///   br label %return
927 /// return:
928 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
929 ///   ret i32 %retval
930 /// @endcode
931 ///
932 /// =>
933 ///
934 /// @code
935 /// bb0:
936 ///   %tmp0 = tail call i32 @f0()
937 ///   ret i32 %tmp0
938 /// bb1:
939 ///   %tmp1 = tail call i32 @f1()
940 ///   ret i32 %tmp1
941 /// bb2:
942 ///   %tmp2 = tail call i32 @f2()
943 ///   ret i32 %tmp2
944 /// @endcode
945 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
946   if (!TLI)
947     return false;
948
949   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
950   if (!RI)
951     return false;
952
953   PHINode *PN = nullptr;
954   BitCastInst *BCI = nullptr;
955   Value *V = RI->getReturnValue();
956   if (V) {
957     BCI = dyn_cast<BitCastInst>(V);
958     if (BCI)
959       V = BCI->getOperand(0);
960
961     PN = dyn_cast<PHINode>(V);
962     if (!PN)
963       return false;
964   }
965
966   if (PN && PN->getParent() != BB)
967     return false;
968
969   // It's not safe to eliminate the sign / zero extension of the return value.
970   // See llvm::isInTailCallPosition().
971   const Function *F = BB->getParent();
972   AttributeSet CallerAttrs = F->getAttributes();
973   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
974       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
975     return false;
976
977   // Make sure there are no instructions between the PHI and return, or that the
978   // return is the first instruction in the block.
979   if (PN) {
980     BasicBlock::iterator BI = BB->begin();
981     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
982     if (&*BI == BCI)
983       // Also skip over the bitcast.
984       ++BI;
985     if (&*BI != RI)
986       return false;
987   } else {
988     BasicBlock::iterator BI = BB->begin();
989     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
990     if (&*BI != RI)
991       return false;
992   }
993
994   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
995   /// call.
996   SmallVector<CallInst*, 4> TailCalls;
997   if (PN) {
998     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
999       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1000       // Make sure the phi value is indeed produced by the tail call.
1001       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1002           TLI->mayBeEmittedAsTailCall(CI))
1003         TailCalls.push_back(CI);
1004     }
1005   } else {
1006     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1007     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1008       if (!VisitedBBs.insert(*PI).second)
1009         continue;
1010
1011       BasicBlock::InstListType &InstList = (*PI)->getInstList();
1012       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1013       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1014       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1015       if (RI == RE)
1016         continue;
1017
1018       CallInst *CI = dyn_cast<CallInst>(&*RI);
1019       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1020         TailCalls.push_back(CI);
1021     }
1022   }
1023
1024   bool Changed = false;
1025   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1026     CallInst *CI = TailCalls[i];
1027     CallSite CS(CI);
1028
1029     // Conservatively require the attributes of the call to match those of the
1030     // return. Ignore noalias because it doesn't affect the call sequence.
1031     AttributeSet CalleeAttrs = CS.getAttributes();
1032     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1033           removeAttribute(Attribute::NoAlias) !=
1034         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1035           removeAttribute(Attribute::NoAlias))
1036       continue;
1037
1038     // Make sure the call instruction is followed by an unconditional branch to
1039     // the return block.
1040     BasicBlock *CallBB = CI->getParent();
1041     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1042     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1043       continue;
1044
1045     // Duplicate the return into CallBB.
1046     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1047     ModifiedDT = Changed = true;
1048     ++NumRetsDup;
1049   }
1050
1051   // If we eliminated all predecessors of the block, delete the block now.
1052   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1053     BB->eraseFromParent();
1054
1055   return Changed;
1056 }
1057
1058 //===----------------------------------------------------------------------===//
1059 // Memory Optimization
1060 //===----------------------------------------------------------------------===//
1061
1062 namespace {
1063
1064 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1065 /// which holds actual Value*'s for register values.
1066 struct ExtAddrMode : public TargetLowering::AddrMode {
1067   Value *BaseReg;
1068   Value *ScaledReg;
1069   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1070   void print(raw_ostream &OS) const;
1071   void dump() const;
1072
1073   bool operator==(const ExtAddrMode& O) const {
1074     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1075            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1076            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1077   }
1078 };
1079
1080 #ifndef NDEBUG
1081 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1082   AM.print(OS);
1083   return OS;
1084 }
1085 #endif
1086
1087 void ExtAddrMode::print(raw_ostream &OS) const {
1088   bool NeedPlus = false;
1089   OS << "[";
1090   if (BaseGV) {
1091     OS << (NeedPlus ? " + " : "")
1092        << "GV:";
1093     BaseGV->printAsOperand(OS, /*PrintType=*/false);
1094     NeedPlus = true;
1095   }
1096
1097   if (BaseOffs) {
1098     OS << (NeedPlus ? " + " : "")
1099        << BaseOffs;
1100     NeedPlus = true;
1101   }
1102
1103   if (BaseReg) {
1104     OS << (NeedPlus ? " + " : "")
1105        << "Base:";
1106     BaseReg->printAsOperand(OS, /*PrintType=*/false);
1107     NeedPlus = true;
1108   }
1109   if (Scale) {
1110     OS << (NeedPlus ? " + " : "")
1111        << Scale << "*";
1112     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1113   }
1114
1115   OS << ']';
1116 }
1117
1118 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1119 void ExtAddrMode::dump() const {
1120   print(dbgs());
1121   dbgs() << '\n';
1122 }
1123 #endif
1124
1125 /// \brief This class provides transaction based operation on the IR.
1126 /// Every change made through this class is recorded in the internal state and
1127 /// can be undone (rollback) until commit is called.
1128 class TypePromotionTransaction {
1129
1130   /// \brief This represents the common interface of the individual transaction.
1131   /// Each class implements the logic for doing one specific modification on
1132   /// the IR via the TypePromotionTransaction.
1133   class TypePromotionAction {
1134   protected:
1135     /// The Instruction modified.
1136     Instruction *Inst;
1137
1138   public:
1139     /// \brief Constructor of the action.
1140     /// The constructor performs the related action on the IR.
1141     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1142
1143     virtual ~TypePromotionAction() {}
1144
1145     /// \brief Undo the modification done by this action.
1146     /// When this method is called, the IR must be in the same state as it was
1147     /// before this action was applied.
1148     /// \pre Undoing the action works if and only if the IR is in the exact same
1149     /// state as it was directly after this action was applied.
1150     virtual void undo() = 0;
1151
1152     /// \brief Advocate every change made by this action.
1153     /// When the results on the IR of the action are to be kept, it is important
1154     /// to call this function, otherwise hidden information may be kept forever.
1155     virtual void commit() {
1156       // Nothing to be done, this action is not doing anything.
1157     }
1158   };
1159
1160   /// \brief Utility to remember the position of an instruction.
1161   class InsertionHandler {
1162     /// Position of an instruction.
1163     /// Either an instruction:
1164     /// - Is the first in a basic block: BB is used.
1165     /// - Has a previous instructon: PrevInst is used.
1166     union {
1167       Instruction *PrevInst;
1168       BasicBlock *BB;
1169     } Point;
1170     /// Remember whether or not the instruction had a previous instruction.
1171     bool HasPrevInstruction;
1172
1173   public:
1174     /// \brief Record the position of \p Inst.
1175     InsertionHandler(Instruction *Inst) {
1176       BasicBlock::iterator It = Inst;
1177       HasPrevInstruction = (It != (Inst->getParent()->begin()));
1178       if (HasPrevInstruction)
1179         Point.PrevInst = --It;
1180       else
1181         Point.BB = Inst->getParent();
1182     }
1183
1184     /// \brief Insert \p Inst at the recorded position.
1185     void insert(Instruction *Inst) {
1186       if (HasPrevInstruction) {
1187         if (Inst->getParent())
1188           Inst->removeFromParent();
1189         Inst->insertAfter(Point.PrevInst);
1190       } else {
1191         Instruction *Position = Point.BB->getFirstInsertionPt();
1192         if (Inst->getParent())
1193           Inst->moveBefore(Position);
1194         else
1195           Inst->insertBefore(Position);
1196       }
1197     }
1198   };
1199
1200   /// \brief Move an instruction before another.
1201   class InstructionMoveBefore : public TypePromotionAction {
1202     /// Original position of the instruction.
1203     InsertionHandler Position;
1204
1205   public:
1206     /// \brief Move \p Inst before \p Before.
1207     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1208         : TypePromotionAction(Inst), Position(Inst) {
1209       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1210       Inst->moveBefore(Before);
1211     }
1212
1213     /// \brief Move the instruction back to its original position.
1214     void undo() override {
1215       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1216       Position.insert(Inst);
1217     }
1218   };
1219
1220   /// \brief Set the operand of an instruction with a new value.
1221   class OperandSetter : public TypePromotionAction {
1222     /// Original operand of the instruction.
1223     Value *Origin;
1224     /// Index of the modified instruction.
1225     unsigned Idx;
1226
1227   public:
1228     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1229     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1230         : TypePromotionAction(Inst), Idx(Idx) {
1231       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1232                    << "for:" << *Inst << "\n"
1233                    << "with:" << *NewVal << "\n");
1234       Origin = Inst->getOperand(Idx);
1235       Inst->setOperand(Idx, NewVal);
1236     }
1237
1238     /// \brief Restore the original value of the instruction.
1239     void undo() override {
1240       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1241                    << "for: " << *Inst << "\n"
1242                    << "with: " << *Origin << "\n");
1243       Inst->setOperand(Idx, Origin);
1244     }
1245   };
1246
1247   /// \brief Hide the operands of an instruction.
1248   /// Do as if this instruction was not using any of its operands.
1249   class OperandsHider : public TypePromotionAction {
1250     /// The list of original operands.
1251     SmallVector<Value *, 4> OriginalValues;
1252
1253   public:
1254     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1255     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1256       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1257       unsigned NumOpnds = Inst->getNumOperands();
1258       OriginalValues.reserve(NumOpnds);
1259       for (unsigned It = 0; It < NumOpnds; ++It) {
1260         // Save the current operand.
1261         Value *Val = Inst->getOperand(It);
1262         OriginalValues.push_back(Val);
1263         // Set a dummy one.
1264         // We could use OperandSetter here, but that would implied an overhead
1265         // that we are not willing to pay.
1266         Inst->setOperand(It, UndefValue::get(Val->getType()));
1267       }
1268     }
1269
1270     /// \brief Restore the original list of uses.
1271     void undo() override {
1272       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1273       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1274         Inst->setOperand(It, OriginalValues[It]);
1275     }
1276   };
1277
1278   /// \brief Build a truncate instruction.
1279   class TruncBuilder : public TypePromotionAction {
1280     Value *Val;
1281   public:
1282     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1283     /// result.
1284     /// trunc Opnd to Ty.
1285     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1286       IRBuilder<> Builder(Opnd);
1287       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1288       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
1289     }
1290
1291     /// \brief Get the built value.
1292     Value *getBuiltValue() { return Val; }
1293
1294     /// \brief Remove the built instruction.
1295     void undo() override {
1296       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1297       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1298         IVal->eraseFromParent();
1299     }
1300   };
1301
1302   /// \brief Build a sign extension instruction.
1303   class SExtBuilder : public TypePromotionAction {
1304     Value *Val;
1305   public:
1306     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1307     /// result.
1308     /// sext Opnd to Ty.
1309     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1310         : TypePromotionAction(InsertPt) {
1311       IRBuilder<> Builder(InsertPt);
1312       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1313       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
1314     }
1315
1316     /// \brief Get the built value.
1317     Value *getBuiltValue() { return Val; }
1318
1319     /// \brief Remove the built instruction.
1320     void undo() override {
1321       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1322       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1323         IVal->eraseFromParent();
1324     }
1325   };
1326
1327   /// \brief Build a zero extension instruction.
1328   class ZExtBuilder : public TypePromotionAction {
1329     Value *Val;
1330   public:
1331     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1332     /// result.
1333     /// zext Opnd to Ty.
1334     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1335         : TypePromotionAction(InsertPt) {
1336       IRBuilder<> Builder(InsertPt);
1337       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1338       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1339     }
1340
1341     /// \brief Get the built value.
1342     Value *getBuiltValue() { return Val; }
1343
1344     /// \brief Remove the built instruction.
1345     void undo() override {
1346       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1347       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1348         IVal->eraseFromParent();
1349     }
1350   };
1351
1352   /// \brief Mutate an instruction to another type.
1353   class TypeMutator : public TypePromotionAction {
1354     /// Record the original type.
1355     Type *OrigTy;
1356
1357   public:
1358     /// \brief Mutate the type of \p Inst into \p NewTy.
1359     TypeMutator(Instruction *Inst, Type *NewTy)
1360         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1361       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1362                    << "\n");
1363       Inst->mutateType(NewTy);
1364     }
1365
1366     /// \brief Mutate the instruction back to its original type.
1367     void undo() override {
1368       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1369                    << "\n");
1370       Inst->mutateType(OrigTy);
1371     }
1372   };
1373
1374   /// \brief Replace the uses of an instruction by another instruction.
1375   class UsesReplacer : public TypePromotionAction {
1376     /// Helper structure to keep track of the replaced uses.
1377     struct InstructionAndIdx {
1378       /// The instruction using the instruction.
1379       Instruction *Inst;
1380       /// The index where this instruction is used for Inst.
1381       unsigned Idx;
1382       InstructionAndIdx(Instruction *Inst, unsigned Idx)
1383           : Inst(Inst), Idx(Idx) {}
1384     };
1385
1386     /// Keep track of the original uses (pair Instruction, Index).
1387     SmallVector<InstructionAndIdx, 4> OriginalUses;
1388     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1389
1390   public:
1391     /// \brief Replace all the use of \p Inst by \p New.
1392     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1393       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1394                    << "\n");
1395       // Record the original uses.
1396       for (Use &U : Inst->uses()) {
1397         Instruction *UserI = cast<Instruction>(U.getUser());
1398         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1399       }
1400       // Now, we can replace the uses.
1401       Inst->replaceAllUsesWith(New);
1402     }
1403
1404     /// \brief Reassign the original uses of Inst to Inst.
1405     void undo() override {
1406       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1407       for (use_iterator UseIt = OriginalUses.begin(),
1408                         EndIt = OriginalUses.end();
1409            UseIt != EndIt; ++UseIt) {
1410         UseIt->Inst->setOperand(UseIt->Idx, Inst);
1411       }
1412     }
1413   };
1414
1415   /// \brief Remove an instruction from the IR.
1416   class InstructionRemover : public TypePromotionAction {
1417     /// Original position of the instruction.
1418     InsertionHandler Inserter;
1419     /// Helper structure to hide all the link to the instruction. In other
1420     /// words, this helps to do as if the instruction was removed.
1421     OperandsHider Hider;
1422     /// Keep track of the uses replaced, if any.
1423     UsesReplacer *Replacer;
1424
1425   public:
1426     /// \brief Remove all reference of \p Inst and optinally replace all its
1427     /// uses with New.
1428     /// \pre If !Inst->use_empty(), then New != nullptr
1429     InstructionRemover(Instruction *Inst, Value *New = nullptr)
1430         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1431           Replacer(nullptr) {
1432       if (New)
1433         Replacer = new UsesReplacer(Inst, New);
1434       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1435       Inst->removeFromParent();
1436     }
1437
1438     ~InstructionRemover() { delete Replacer; }
1439
1440     /// \brief Really remove the instruction.
1441     void commit() override { delete Inst; }
1442
1443     /// \brief Resurrect the instruction and reassign it to the proper uses if
1444     /// new value was provided when build this action.
1445     void undo() override {
1446       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1447       Inserter.insert(Inst);
1448       if (Replacer)
1449         Replacer->undo();
1450       Hider.undo();
1451     }
1452   };
1453
1454 public:
1455   /// Restoration point.
1456   /// The restoration point is a pointer to an action instead of an iterator
1457   /// because the iterator may be invalidated but not the pointer.
1458   typedef const TypePromotionAction *ConstRestorationPt;
1459   /// Advocate every changes made in that transaction.
1460   void commit();
1461   /// Undo all the changes made after the given point.
1462   void rollback(ConstRestorationPt Point);
1463   /// Get the current restoration point.
1464   ConstRestorationPt getRestorationPoint() const;
1465
1466   /// \name API for IR modification with state keeping to support rollback.
1467   /// @{
1468   /// Same as Instruction::setOperand.
1469   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1470   /// Same as Instruction::eraseFromParent.
1471   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1472   /// Same as Value::replaceAllUsesWith.
1473   void replaceAllUsesWith(Instruction *Inst, Value *New);
1474   /// Same as Value::mutateType.
1475   void mutateType(Instruction *Inst, Type *NewTy);
1476   /// Same as IRBuilder::createTrunc.
1477   Value *createTrunc(Instruction *Opnd, Type *Ty);
1478   /// Same as IRBuilder::createSExt.
1479   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1480   /// Same as IRBuilder::createZExt.
1481   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
1482   /// Same as Instruction::moveBefore.
1483   void moveBefore(Instruction *Inst, Instruction *Before);
1484   /// @}
1485
1486 private:
1487   /// The ordered list of actions made so far.
1488   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1489   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1490 };
1491
1492 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1493                                           Value *NewVal) {
1494   Actions.push_back(
1495       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1496 }
1497
1498 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1499                                                 Value *NewVal) {
1500   Actions.push_back(
1501       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1502 }
1503
1504 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1505                                                   Value *New) {
1506   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1507 }
1508
1509 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1510   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1511 }
1512
1513 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1514                                              Type *Ty) {
1515   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1516   Value *Val = Ptr->getBuiltValue();
1517   Actions.push_back(std::move(Ptr));
1518   return Val;
1519 }
1520
1521 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1522                                             Value *Opnd, Type *Ty) {
1523   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1524   Value *Val = Ptr->getBuiltValue();
1525   Actions.push_back(std::move(Ptr));
1526   return Val;
1527 }
1528
1529 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1530                                             Value *Opnd, Type *Ty) {
1531   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
1532   Value *Val = Ptr->getBuiltValue();
1533   Actions.push_back(std::move(Ptr));
1534   return Val;
1535 }
1536
1537 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1538                                           Instruction *Before) {
1539   Actions.push_back(
1540       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1541 }
1542
1543 TypePromotionTransaction::ConstRestorationPt
1544 TypePromotionTransaction::getRestorationPoint() const {
1545   return !Actions.empty() ? Actions.back().get() : nullptr;
1546 }
1547
1548 void TypePromotionTransaction::commit() {
1549   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1550        ++It)
1551     (*It)->commit();
1552   Actions.clear();
1553 }
1554
1555 void TypePromotionTransaction::rollback(
1556     TypePromotionTransaction::ConstRestorationPt Point) {
1557   while (!Actions.empty() && Point != Actions.back().get()) {
1558     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1559     Curr->undo();
1560   }
1561 }
1562
1563 /// \brief A helper class for matching addressing modes.
1564 ///
1565 /// This encapsulates the logic for matching the target-legal addressing modes.
1566 class AddressingModeMatcher {
1567   SmallVectorImpl<Instruction*> &AddrModeInsts;
1568   const TargetLowering &TLI;
1569
1570   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1571   /// the memory instruction that we're computing this address for.
1572   Type *AccessTy;
1573   Instruction *MemoryInst;
1574
1575   /// AddrMode - This is the addressing mode that we're building up.  This is
1576   /// part of the return value of this addressing mode matching stuff.
1577   ExtAddrMode &AddrMode;
1578
1579   /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1580   const SetOfInstrs &InsertedTruncs;
1581   /// A map from the instructions to their type before promotion.
1582   InstrToOrigTy &PromotedInsts;
1583   /// The ongoing transaction where every action should be registered.
1584   TypePromotionTransaction &TPT;
1585
1586   /// IgnoreProfitability - This is set to true when we should not do
1587   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
1588   /// always returns true.
1589   bool IgnoreProfitability;
1590
1591   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1592                         const TargetLowering &T, Type *AT,
1593                         Instruction *MI, ExtAddrMode &AM,
1594                         const SetOfInstrs &InsertedTruncs,
1595                         InstrToOrigTy &PromotedInsts,
1596                         TypePromotionTransaction &TPT)
1597       : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1598         InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1599     IgnoreProfitability = false;
1600   }
1601 public:
1602
1603   /// Match - Find the maximal addressing mode that a load/store of V can fold,
1604   /// give an access type of AccessTy.  This returns a list of involved
1605   /// instructions in AddrModeInsts.
1606   /// \p InsertedTruncs The truncate instruction inserted by other
1607   /// CodeGenPrepare
1608   /// optimizations.
1609   /// \p PromotedInsts maps the instructions to their type before promotion.
1610   /// \p The ongoing transaction where every action should be registered.
1611   static ExtAddrMode Match(Value *V, Type *AccessTy,
1612                            Instruction *MemoryInst,
1613                            SmallVectorImpl<Instruction*> &AddrModeInsts,
1614                            const TargetLowering &TLI,
1615                            const SetOfInstrs &InsertedTruncs,
1616                            InstrToOrigTy &PromotedInsts,
1617                            TypePromotionTransaction &TPT) {
1618     ExtAddrMode Result;
1619
1620     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1621                                          MemoryInst, Result, InsertedTruncs,
1622                                          PromotedInsts, TPT).MatchAddr(V, 0);
1623     (void)Success; assert(Success && "Couldn't select *anything*?");
1624     return Result;
1625   }
1626 private:
1627   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1628   bool MatchAddr(Value *V, unsigned Depth);
1629   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1630                           bool *MovedAway = nullptr);
1631   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1632                                             ExtAddrMode &AMBefore,
1633                                             ExtAddrMode &AMAfter);
1634   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1635   bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1636                              Value *PromotedOperand) const;
1637 };
1638
1639 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1640 /// Return true and update AddrMode if this addr mode is legal for the target,
1641 /// false if not.
1642 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1643                                              unsigned Depth) {
1644   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1645   // mode.  Just process that directly.
1646   if (Scale == 1)
1647     return MatchAddr(ScaleReg, Depth);
1648
1649   // If the scale is 0, it takes nothing to add this.
1650   if (Scale == 0)
1651     return true;
1652
1653   // If we already have a scale of this value, we can add to it, otherwise, we
1654   // need an available scale field.
1655   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1656     return false;
1657
1658   ExtAddrMode TestAddrMode = AddrMode;
1659
1660   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
1661   // [A+B + A*7] -> [B+A*8].
1662   TestAddrMode.Scale += Scale;
1663   TestAddrMode.ScaledReg = ScaleReg;
1664
1665   // If the new address isn't legal, bail out.
1666   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1667     return false;
1668
1669   // It was legal, so commit it.
1670   AddrMode = TestAddrMode;
1671
1672   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
1673   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
1674   // X*Scale + C*Scale to addr mode.
1675   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
1676   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
1677       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1678     TestAddrMode.ScaledReg = AddLHS;
1679     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1680
1681     // If this addressing mode is legal, commit it and remember that we folded
1682     // this instruction.
1683     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1684       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1685       AddrMode = TestAddrMode;
1686       return true;
1687     }
1688   }
1689
1690   // Otherwise, not (x+c)*scale, just return what we have.
1691   return true;
1692 }
1693
1694 /// MightBeFoldableInst - This is a little filter, which returns true if an
1695 /// addressing computation involving I might be folded into a load/store
1696 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
1697 /// the set of instructions that MatchOperationAddr can.
1698 static bool MightBeFoldableInst(Instruction *I) {
1699   switch (I->getOpcode()) {
1700   case Instruction::BitCast:
1701   case Instruction::AddrSpaceCast:
1702     // Don't touch identity bitcasts.
1703     if (I->getType() == I->getOperand(0)->getType())
1704       return false;
1705     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1706   case Instruction::PtrToInt:
1707     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1708     return true;
1709   case Instruction::IntToPtr:
1710     // We know the input is intptr_t, so this is foldable.
1711     return true;
1712   case Instruction::Add:
1713     return true;
1714   case Instruction::Mul:
1715   case Instruction::Shl:
1716     // Can only handle X*C and X << C.
1717     return isa<ConstantInt>(I->getOperand(1));
1718   case Instruction::GetElementPtr:
1719     return true;
1720   default:
1721     return false;
1722   }
1723 }
1724
1725 /// \brief Hepler class to perform type promotion.
1726 class TypePromotionHelper {
1727   /// \brief Utility function to check whether or not a sign or zero extension
1728   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1729   /// either using the operands of \p Inst or promoting \p Inst.
1730   /// The type of the extension is defined by \p IsSExt.
1731   /// In other words, check if:
1732   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
1733   /// #1 Promotion applies:
1734   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
1735   /// #2 Operand reuses:
1736   /// ext opnd1 to ConsideredExtType.
1737   /// \p PromotedInsts maps the instructions to their type before promotion.
1738   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
1739                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
1740
1741   /// \brief Utility function to determine if \p OpIdx should be promoted when
1742   /// promoting \p Inst.
1743   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
1744     if (isa<SelectInst>(Inst) && OpIdx == 0)
1745       return false;
1746     return true;
1747   }
1748
1749   /// \brief Utility function to promote the operand of \p Ext when this
1750   /// operand is a promotable trunc or sext or zext.
1751   /// \p PromotedInsts maps the instructions to their type before promotion.
1752   /// \p CreatedInsts[out] contains how many non-free instructions have been
1753   /// created to promote the operand of Ext.
1754   /// Should never be called directly.
1755   /// \return The promoted value which is used instead of Ext.
1756   static Value *promoteOperandForTruncAndAnyExt(Instruction *Ext,
1757                                                 TypePromotionTransaction &TPT,
1758                                                 InstrToOrigTy &PromotedInsts,
1759                                                 unsigned &CreatedInsts);
1760
1761   /// \brief Utility function to promote the operand of \p Ext when this
1762   /// operand is promotable and is not a supported trunc or sext.
1763   /// \p PromotedInsts maps the instructions to their type before promotion.
1764   /// \p CreatedInsts[out] contains how many non-free instructions have been
1765   /// created to promote the operand of Ext.
1766   /// Should never be called directly.
1767   /// \return The promoted value which is used instead of Ext.
1768   static Value *promoteOperandForOther(Instruction *Ext,
1769                                        TypePromotionTransaction &TPT,
1770                                        InstrToOrigTy &PromotedInsts,
1771                                        unsigned &CreatedInsts, bool IsSExt);
1772
1773   /// \see promoteOperandForOther.
1774   static Value *signExtendOperandForOther(Instruction *Ext,
1775                                           TypePromotionTransaction &TPT,
1776                                           InstrToOrigTy &PromotedInsts,
1777                                           unsigned &CreatedInsts) {
1778     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, true);
1779   }
1780
1781   /// \see promoteOperandForOther.
1782   static Value *zeroExtendOperandForOther(Instruction *Ext,
1783                                           TypePromotionTransaction &TPT,
1784                                           InstrToOrigTy &PromotedInsts,
1785                                           unsigned &CreatedInsts) {
1786     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, false);
1787   }
1788
1789 public:
1790   /// Type for the utility function that promotes the operand of Ext.
1791   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
1792                            InstrToOrigTy &PromotedInsts,
1793                            unsigned &CreatedInsts);
1794   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
1795   /// action to promote the operand of \p Ext instead of using Ext.
1796   /// \return NULL if no promotable action is possible with the current
1797   /// sign extension.
1798   /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1799   /// the others CodeGenPrepare optimizations. This information is important
1800   /// because we do not want to promote these instructions as CodeGenPrepare
1801   /// will reinsert them later. Thus creating an infinite loop: create/remove.
1802   /// \p PromotedInsts maps the instructions to their type before promotion.
1803   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
1804                           const TargetLowering &TLI,
1805                           const InstrToOrigTy &PromotedInsts);
1806 };
1807
1808 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1809                                         Type *ConsideredExtType,
1810                                         const InstrToOrigTy &PromotedInsts,
1811                                         bool IsSExt) {
1812   // We can always get through zext.
1813   if (isa<ZExtInst>(Inst))
1814     return true;
1815
1816   // sext(sext) is ok too.
1817   if (IsSExt && isa<SExtInst>(Inst))
1818     return true;
1819
1820   // We can get through binary operator, if it is legal. In other words, the
1821   // binary operator must have a nuw or nsw flag.
1822   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1823   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1824       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
1825        (IsSExt && BinOp->hasNoSignedWrap())))
1826     return true;
1827
1828   // Check if we can do the following simplification.
1829   // ext(trunc(opnd)) --> ext(opnd)
1830   if (!isa<TruncInst>(Inst))
1831     return false;
1832
1833   Value *OpndVal = Inst->getOperand(0);
1834   // Check if we can use this operand in the extension.
1835   // If the type is larger than the result type of the extension,
1836   // we cannot.
1837   if (OpndVal->getType()->getIntegerBitWidth() >
1838       ConsideredExtType->getIntegerBitWidth())
1839     return false;
1840
1841   // If the operand of the truncate is not an instruction, we will not have
1842   // any information on the dropped bits.
1843   // (Actually we could for constant but it is not worth the extra logic).
1844   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1845   if (!Opnd)
1846     return false;
1847
1848   // Check if the source of the type is narrow enough.
1849   // I.e., check that trunc just drops extended bits of the same kind of
1850   // the extension.
1851   // #1 get the type of the operand and check the kind of the extended bits.
1852   const Type *OpndType;
1853   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1854   if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
1855     OpndType = It->second.Ty;
1856   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
1857     OpndType = Opnd->getOperand(0)->getType();
1858   else
1859     return false;
1860
1861   // #2 check that the truncate just drop extended bits.
1862   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1863     return true;
1864
1865   return false;
1866 }
1867
1868 TypePromotionHelper::Action TypePromotionHelper::getAction(
1869     Instruction *Ext, const SetOfInstrs &InsertedTruncs,
1870     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1871   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
1872          "Unexpected instruction type");
1873   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
1874   Type *ExtTy = Ext->getType();
1875   bool IsSExt = isa<SExtInst>(Ext);
1876   // If the operand of the extension is not an instruction, we cannot
1877   // get through.
1878   // If it, check we can get through.
1879   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
1880     return nullptr;
1881
1882   // Do not promote if the operand has been added by codegenprepare.
1883   // Otherwise, it means we are undoing an optimization that is likely to be
1884   // redone, thus causing potential infinite loop.
1885   if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
1886     return nullptr;
1887
1888   // SExt or Trunc instructions.
1889   // Return the related handler.
1890   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
1891       isa<ZExtInst>(ExtOpnd))
1892     return promoteOperandForTruncAndAnyExt;
1893
1894   // Regular instruction.
1895   // Abort early if we will have to insert non-free instructions.
1896   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
1897     return nullptr;
1898   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
1899 }
1900
1901 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
1902     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1903     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1904   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1905   // get through it and this method should not be called.
1906   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1907   Value *ExtVal = SExt;
1908   if (isa<ZExtInst>(SExtOpnd)) {
1909     // Replace s|zext(zext(opnd))
1910     // => zext(opnd).
1911     Value *ZExt =
1912         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1913     TPT.replaceAllUsesWith(SExt, ZExt);
1914     TPT.eraseInstruction(SExt);
1915     ExtVal = ZExt;
1916   } else {
1917     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
1918     // => z|sext(opnd).
1919     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1920   }
1921   CreatedInsts = 0;
1922
1923   // Remove dead code.
1924   if (SExtOpnd->use_empty())
1925     TPT.eraseInstruction(SExtOpnd);
1926
1927   // Check if the extension is still needed.
1928   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1929   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
1930     return ExtVal;
1931
1932   // At this point we have: ext ty opnd to ty.
1933   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1934   Value *NextVal = ExtInst->getOperand(0);
1935   TPT.eraseInstruction(ExtInst, NextVal);
1936   return NextVal;
1937 }
1938
1939 Value *TypePromotionHelper::promoteOperandForOther(
1940     Instruction *Ext, TypePromotionTransaction &TPT,
1941     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts, bool IsSExt) {
1942   // By construction, the operand of Ext is an instruction. Otherwise we cannot
1943   // get through it and this method should not be called.
1944   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
1945   CreatedInsts = 0;
1946   if (!ExtOpnd->hasOneUse()) {
1947     // ExtOpnd will be promoted.
1948     // All its uses, but Ext, will need to use a truncated value of the
1949     // promoted version.
1950     // Create the truncate now.
1951     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
1952     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
1953       ITrunc->removeFromParent();
1954       // Insert it just after the definition.
1955       ITrunc->insertAfter(ExtOpnd);
1956     }
1957
1958     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
1959     // Restore the operand of Ext (which has been replace by the previous call
1960     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1961     TPT.setOperand(Ext, 0, ExtOpnd);
1962   }
1963
1964   // Get through the Instruction:
1965   // 1. Update its type.
1966   // 2. Replace the uses of Ext by Inst.
1967   // 3. Extend each operand that needs to be extended.
1968
1969   // Remember the original type of the instruction before promotion.
1970   // This is useful to know that the high bits are sign extended bits.
1971   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
1972       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
1973   // Step #1.
1974   TPT.mutateType(ExtOpnd, Ext->getType());
1975   // Step #2.
1976   TPT.replaceAllUsesWith(Ext, ExtOpnd);
1977   // Step #3.
1978   Instruction *ExtForOpnd = Ext;
1979
1980   DEBUG(dbgs() << "Propagate Ext to operands\n");
1981   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1982        ++OpIdx) {
1983     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
1984     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
1985         !shouldExtOperand(ExtOpnd, OpIdx)) {
1986       DEBUG(dbgs() << "No need to propagate\n");
1987       continue;
1988     }
1989     // Check if we can statically extend the operand.
1990     Value *Opnd = ExtOpnd->getOperand(OpIdx);
1991     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1992       DEBUG(dbgs() << "Statically extend\n");
1993       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
1994       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
1995                             : Cst->getValue().zext(BitWidth);
1996       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
1997       continue;
1998     }
1999     // UndefValue are typed, so we have to statically sign extend them.
2000     if (isa<UndefValue>(Opnd)) {
2001       DEBUG(dbgs() << "Statically extend\n");
2002       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
2003       continue;
2004     }
2005
2006     // Otherwise we have to explicity sign extend the operand.
2007     // Check if Ext was reused to extend an operand.
2008     if (!ExtForOpnd) {
2009       // If yes, create a new one.
2010       DEBUG(dbgs() << "More operands to ext\n");
2011       ExtForOpnd =
2012           cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2013                                    : TPT.createZExt(Ext, Opnd, Ext->getType()));
2014       ++CreatedInsts;
2015     }
2016
2017     TPT.setOperand(ExtForOpnd, 0, Opnd);
2018
2019     // Move the sign extension before the insertion point.
2020     TPT.moveBefore(ExtForOpnd, ExtOpnd);
2021     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2022     // If more sext are required, new instructions will have to be created.
2023     ExtForOpnd = nullptr;
2024   }
2025   if (ExtForOpnd == Ext) {
2026     DEBUG(dbgs() << "Extension is useless now\n");
2027     TPT.eraseInstruction(Ext);
2028   }
2029   return ExtOpnd;
2030 }
2031
2032 /// IsPromotionProfitable - Check whether or not promoting an instruction
2033 /// to a wider type was profitable.
2034 /// \p MatchedSize gives the number of instructions that have been matched
2035 /// in the addressing mode after the promotion was applied.
2036 /// \p SizeWithPromotion gives the number of created instructions for
2037 /// the promotion plus the number of instructions that have been
2038 /// matched in the addressing mode before the promotion.
2039 /// \p PromotedOperand is the value that has been promoted.
2040 /// \return True if the promotion is profitable, false otherwise.
2041 bool
2042 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2043                                              unsigned SizeWithPromotion,
2044                                              Value *PromotedOperand) const {
2045   // We folded less instructions than what we created to promote the operand.
2046   // This is not profitable.
2047   if (MatchedSize < SizeWithPromotion)
2048     return false;
2049   if (MatchedSize > SizeWithPromotion)
2050     return true;
2051   // The promotion is neutral but it may help folding the sign extension in
2052   // loads for instance.
2053   // Check that we did not create an illegal instruction.
2054   Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2055   if (!PromotedInst)
2056     return false;
2057   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2058   // If the ISDOpcode is undefined, it was undefined before the promotion.
2059   if (!ISDOpcode)
2060     return true;
2061   // Otherwise, check if the promoted instruction is legal or not.
2062   return TLI.isOperationLegalOrCustom(
2063       ISDOpcode, TLI.getValueType(PromotedInst->getType()));
2064 }
2065
2066 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2067 /// fold the operation into the addressing mode.  If so, update the addressing
2068 /// mode and return true, otherwise return false without modifying AddrMode.
2069 /// If \p MovedAway is not NULL, it contains the information of whether or
2070 /// not AddrInst has to be folded into the addressing mode on success.
2071 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2072 /// because it has been moved away.
2073 /// Thus AddrInst must not be added in the matched instructions.
2074 /// This state can happen when AddrInst is a sext, since it may be moved away.
2075 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2076 /// not be referenced anymore.
2077 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2078                                                unsigned Depth,
2079                                                bool *MovedAway) {
2080   // Avoid exponential behavior on extremely deep expression trees.
2081   if (Depth >= 5) return false;
2082
2083   // By default, all matched instructions stay in place.
2084   if (MovedAway)
2085     *MovedAway = false;
2086
2087   switch (Opcode) {
2088   case Instruction::PtrToInt:
2089     // PtrToInt is always a noop, as we know that the int type is pointer sized.
2090     return MatchAddr(AddrInst->getOperand(0), Depth);
2091   case Instruction::IntToPtr:
2092     // This inttoptr is a no-op if the integer type is pointer sized.
2093     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
2094         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
2095       return MatchAddr(AddrInst->getOperand(0), Depth);
2096     return false;
2097   case Instruction::BitCast:
2098   case Instruction::AddrSpaceCast:
2099     // BitCast is always a noop, and we can handle it as long as it is
2100     // int->int or pointer->pointer (we don't want int<->fp or something).
2101     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2102          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2103         // Don't touch identity bitcasts.  These were probably put here by LSR,
2104         // and we don't want to mess around with them.  Assume it knows what it
2105         // is doing.
2106         AddrInst->getOperand(0)->getType() != AddrInst->getType())
2107       return MatchAddr(AddrInst->getOperand(0), Depth);
2108     return false;
2109   case Instruction::Add: {
2110     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
2111     ExtAddrMode BackupAddrMode = AddrMode;
2112     unsigned OldSize = AddrModeInsts.size();
2113     // Start a transaction at this point.
2114     // The LHS may match but not the RHS.
2115     // Therefore, we need a higher level restoration point to undo partially
2116     // matched operation.
2117     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2118         TPT.getRestorationPoint();
2119
2120     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2121         MatchAddr(AddrInst->getOperand(0), Depth+1))
2122       return true;
2123
2124     // Restore the old addr mode info.
2125     AddrMode = BackupAddrMode;
2126     AddrModeInsts.resize(OldSize);
2127     TPT.rollback(LastKnownGood);
2128
2129     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
2130     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2131         MatchAddr(AddrInst->getOperand(1), Depth+1))
2132       return true;
2133
2134     // Otherwise we definitely can't merge the ADD in.
2135     AddrMode = BackupAddrMode;
2136     AddrModeInsts.resize(OldSize);
2137     TPT.rollback(LastKnownGood);
2138     break;
2139   }
2140   //case Instruction::Or:
2141   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2142   //break;
2143   case Instruction::Mul:
2144   case Instruction::Shl: {
2145     // Can only handle X*C and X << C.
2146     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2147     if (!RHS)
2148       return false;
2149     int64_t Scale = RHS->getSExtValue();
2150     if (Opcode == Instruction::Shl)
2151       Scale = 1LL << Scale;
2152
2153     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2154   }
2155   case Instruction::GetElementPtr: {
2156     // Scan the GEP.  We check it if it contains constant offsets and at most
2157     // one variable offset.
2158     int VariableOperand = -1;
2159     unsigned VariableScale = 0;
2160
2161     int64_t ConstantOffset = 0;
2162     const DataLayout *TD = TLI.getDataLayout();
2163     gep_type_iterator GTI = gep_type_begin(AddrInst);
2164     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2165       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2166         const StructLayout *SL = TD->getStructLayout(STy);
2167         unsigned Idx =
2168           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2169         ConstantOffset += SL->getElementOffset(Idx);
2170       } else {
2171         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2172         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2173           ConstantOffset += CI->getSExtValue()*TypeSize;
2174         } else if (TypeSize) {  // Scales of zero don't do anything.
2175           // We only allow one variable index at the moment.
2176           if (VariableOperand != -1)
2177             return false;
2178
2179           // Remember the variable index.
2180           VariableOperand = i;
2181           VariableScale = TypeSize;
2182         }
2183       }
2184     }
2185
2186     // A common case is for the GEP to only do a constant offset.  In this case,
2187     // just add it to the disp field and check validity.
2188     if (VariableOperand == -1) {
2189       AddrMode.BaseOffs += ConstantOffset;
2190       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2191         // Check to see if we can fold the base pointer in too.
2192         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2193           return true;
2194       }
2195       AddrMode.BaseOffs -= ConstantOffset;
2196       return false;
2197     }
2198
2199     // Save the valid addressing mode in case we can't match.
2200     ExtAddrMode BackupAddrMode = AddrMode;
2201     unsigned OldSize = AddrModeInsts.size();
2202
2203     // See if the scale and offset amount is valid for this target.
2204     AddrMode.BaseOffs += ConstantOffset;
2205
2206     // Match the base operand of the GEP.
2207     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2208       // If it couldn't be matched, just stuff the value in a register.
2209       if (AddrMode.HasBaseReg) {
2210         AddrMode = BackupAddrMode;
2211         AddrModeInsts.resize(OldSize);
2212         return false;
2213       }
2214       AddrMode.HasBaseReg = true;
2215       AddrMode.BaseReg = AddrInst->getOperand(0);
2216     }
2217
2218     // Match the remaining variable portion of the GEP.
2219     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2220                           Depth)) {
2221       // If it couldn't be matched, try stuffing the base into a register
2222       // instead of matching it, and retrying the match of the scale.
2223       AddrMode = BackupAddrMode;
2224       AddrModeInsts.resize(OldSize);
2225       if (AddrMode.HasBaseReg)
2226         return false;
2227       AddrMode.HasBaseReg = true;
2228       AddrMode.BaseReg = AddrInst->getOperand(0);
2229       AddrMode.BaseOffs += ConstantOffset;
2230       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2231                             VariableScale, Depth)) {
2232         // If even that didn't work, bail.
2233         AddrMode = BackupAddrMode;
2234         AddrModeInsts.resize(OldSize);
2235         return false;
2236       }
2237     }
2238
2239     return true;
2240   }
2241   case Instruction::SExt:
2242   case Instruction::ZExt: {
2243     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2244     if (!Ext)
2245       return false;
2246
2247     // Try to move this ext out of the way of the addressing mode.
2248     // Ask for a method for doing so.
2249     TypePromotionHelper::Action TPH =
2250         TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
2251     if (!TPH)
2252       return false;
2253
2254     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2255         TPT.getRestorationPoint();
2256     unsigned CreatedInsts = 0;
2257     Value *PromotedOperand = TPH(Ext, TPT, PromotedInsts, CreatedInsts);
2258     // SExt has been moved away.
2259     // Thus either it will be rematched later in the recursive calls or it is
2260     // gone. Anyway, we must not fold it into the addressing mode at this point.
2261     // E.g.,
2262     // op = add opnd, 1
2263     // idx = ext op
2264     // addr = gep base, idx
2265     // is now:
2266     // promotedOpnd = ext opnd            <- no match here
2267     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
2268     // addr = gep base, op                <- match
2269     if (MovedAway)
2270       *MovedAway = true;
2271
2272     assert(PromotedOperand &&
2273            "TypePromotionHelper should have filtered out those cases");
2274
2275     ExtAddrMode BackupAddrMode = AddrMode;
2276     unsigned OldSize = AddrModeInsts.size();
2277
2278     if (!MatchAddr(PromotedOperand, Depth) ||
2279         !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2280                                PromotedOperand)) {
2281       AddrMode = BackupAddrMode;
2282       AddrModeInsts.resize(OldSize);
2283       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2284       TPT.rollback(LastKnownGood);
2285       return false;
2286     }
2287     return true;
2288   }
2289   }
2290   return false;
2291 }
2292
2293 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2294 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
2295 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
2296 /// or intptr_t for the target.
2297 ///
2298 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2299   // Start a transaction at this point that we will rollback if the matching
2300   // fails.
2301   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2302       TPT.getRestorationPoint();
2303   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2304     // Fold in immediates if legal for the target.
2305     AddrMode.BaseOffs += CI->getSExtValue();
2306     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2307       return true;
2308     AddrMode.BaseOffs -= CI->getSExtValue();
2309   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2310     // If this is a global variable, try to fold it into the addressing mode.
2311     if (!AddrMode.BaseGV) {
2312       AddrMode.BaseGV = GV;
2313       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2314         return true;
2315       AddrMode.BaseGV = nullptr;
2316     }
2317   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2318     ExtAddrMode BackupAddrMode = AddrMode;
2319     unsigned OldSize = AddrModeInsts.size();
2320
2321     // Check to see if it is possible to fold this operation.
2322     bool MovedAway = false;
2323     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2324       // This instruction may have been move away. If so, there is nothing
2325       // to check here.
2326       if (MovedAway)
2327         return true;
2328       // Okay, it's possible to fold this.  Check to see if it is actually
2329       // *profitable* to do so.  We use a simple cost model to avoid increasing
2330       // register pressure too much.
2331       if (I->hasOneUse() ||
2332           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2333         AddrModeInsts.push_back(I);
2334         return true;
2335       }
2336
2337       // It isn't profitable to do this, roll back.
2338       //cerr << "NOT FOLDING: " << *I;
2339       AddrMode = BackupAddrMode;
2340       AddrModeInsts.resize(OldSize);
2341       TPT.rollback(LastKnownGood);
2342     }
2343   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2344     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2345       return true;
2346     TPT.rollback(LastKnownGood);
2347   } else if (isa<ConstantPointerNull>(Addr)) {
2348     // Null pointer gets folded without affecting the addressing mode.
2349     return true;
2350   }
2351
2352   // Worse case, the target should support [reg] addressing modes. :)
2353   if (!AddrMode.HasBaseReg) {
2354     AddrMode.HasBaseReg = true;
2355     AddrMode.BaseReg = Addr;
2356     // Still check for legality in case the target supports [imm] but not [i+r].
2357     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2358       return true;
2359     AddrMode.HasBaseReg = false;
2360     AddrMode.BaseReg = nullptr;
2361   }
2362
2363   // If the base register is already taken, see if we can do [r+r].
2364   if (AddrMode.Scale == 0) {
2365     AddrMode.Scale = 1;
2366     AddrMode.ScaledReg = Addr;
2367     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2368       return true;
2369     AddrMode.Scale = 0;
2370     AddrMode.ScaledReg = nullptr;
2371   }
2372   // Couldn't match.
2373   TPT.rollback(LastKnownGood);
2374   return false;
2375 }
2376
2377 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2378 /// inline asm call are due to memory operands.  If so, return true, otherwise
2379 /// return false.
2380 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2381                                     const TargetLowering &TLI) {
2382   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2383   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2384     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2385
2386     // Compute the constraint code and ConstraintType to use.
2387     TLI.ComputeConstraintToUse(OpInfo, SDValue());
2388
2389     // If this asm operand is our Value*, and if it isn't an indirect memory
2390     // operand, we can't fold it!
2391     if (OpInfo.CallOperandVal == OpVal &&
2392         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2393          !OpInfo.isIndirect))
2394       return false;
2395   }
2396
2397   return true;
2398 }
2399
2400 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2401 /// memory use.  If we find an obviously non-foldable instruction, return true.
2402 /// Add the ultimately found memory instructions to MemoryUses.
2403 static bool FindAllMemoryUses(Instruction *I,
2404                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2405                               SmallPtrSetImpl<Instruction*> &ConsideredInsts,
2406                               const TargetLowering &TLI) {
2407   // If we already considered this instruction, we're done.
2408   if (!ConsideredInsts.insert(I).second)
2409     return false;
2410
2411   // If this is an obviously unfoldable instruction, bail out.
2412   if (!MightBeFoldableInst(I))
2413     return true;
2414
2415   // Loop over all the uses, recursively processing them.
2416   for (Use &U : I->uses()) {
2417     Instruction *UserI = cast<Instruction>(U.getUser());
2418
2419     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2420       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2421       continue;
2422     }
2423
2424     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2425       unsigned opNo = U.getOperandNo();
2426       if (opNo == 0) return true; // Storing addr, not into addr.
2427       MemoryUses.push_back(std::make_pair(SI, opNo));
2428       continue;
2429     }
2430
2431     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2432       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2433       if (!IA) return true;
2434
2435       // If this is a memory operand, we're cool, otherwise bail out.
2436       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2437         return true;
2438       continue;
2439     }
2440
2441     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2442       return true;
2443   }
2444
2445   return false;
2446 }
2447
2448 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2449 /// the use site that we're folding it into.  If so, there is no cost to
2450 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
2451 /// that we know are live at the instruction already.
2452 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2453                                                    Value *KnownLive2) {
2454   // If Val is either of the known-live values, we know it is live!
2455   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2456     return true;
2457
2458   // All values other than instructions and arguments (e.g. constants) are live.
2459   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2460
2461   // If Val is a constant sized alloca in the entry block, it is live, this is
2462   // true because it is just a reference to the stack/frame pointer, which is
2463   // live for the whole function.
2464   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2465     if (AI->isStaticAlloca())
2466       return true;
2467
2468   // Check to see if this value is already used in the memory instruction's
2469   // block.  If so, it's already live into the block at the very least, so we
2470   // can reasonably fold it.
2471   return Val->isUsedInBasicBlock(MemoryInst->getParent());
2472 }
2473
2474 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2475 /// mode of the machine to fold the specified instruction into a load or store
2476 /// that ultimately uses it.  However, the specified instruction has multiple
2477 /// uses.  Given this, it may actually increase register pressure to fold it
2478 /// into the load.  For example, consider this code:
2479 ///
2480 ///     X = ...
2481 ///     Y = X+1
2482 ///     use(Y)   -> nonload/store
2483 ///     Z = Y+1
2484 ///     load Z
2485 ///
2486 /// In this case, Y has multiple uses, and can be folded into the load of Z
2487 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
2488 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
2489 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
2490 /// number of computations either.
2491 ///
2492 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
2493 /// X was live across 'load Z' for other reasons, we actually *would* want to
2494 /// fold the addressing mode in the Z case.  This would make Y die earlier.
2495 bool AddressingModeMatcher::
2496 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2497                                      ExtAddrMode &AMAfter) {
2498   if (IgnoreProfitability) return true;
2499
2500   // AMBefore is the addressing mode before this instruction was folded into it,
2501   // and AMAfter is the addressing mode after the instruction was folded.  Get
2502   // the set of registers referenced by AMAfter and subtract out those
2503   // referenced by AMBefore: this is the set of values which folding in this
2504   // address extends the lifetime of.
2505   //
2506   // Note that there are only two potential values being referenced here,
2507   // BaseReg and ScaleReg (global addresses are always available, as are any
2508   // folded immediates).
2509   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2510
2511   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2512   // lifetime wasn't extended by adding this instruction.
2513   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2514     BaseReg = nullptr;
2515   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2516     ScaledReg = nullptr;
2517
2518   // If folding this instruction (and it's subexprs) didn't extend any live
2519   // ranges, we're ok with it.
2520   if (!BaseReg && !ScaledReg)
2521     return true;
2522
2523   // If all uses of this instruction are ultimately load/store/inlineasm's,
2524   // check to see if their addressing modes will include this instruction.  If
2525   // so, we can fold it into all uses, so it doesn't matter if it has multiple
2526   // uses.
2527   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2528   SmallPtrSet<Instruction*, 16> ConsideredInsts;
2529   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2530     return false;  // Has a non-memory, non-foldable use!
2531
2532   // Now that we know that all uses of this instruction are part of a chain of
2533   // computation involving only operations that could theoretically be folded
2534   // into a memory use, loop over each of these uses and see if they could
2535   // *actually* fold the instruction.
2536   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2537   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2538     Instruction *User = MemoryUses[i].first;
2539     unsigned OpNo = MemoryUses[i].second;
2540
2541     // Get the access type of this use.  If the use isn't a pointer, we don't
2542     // know what it accesses.
2543     Value *Address = User->getOperand(OpNo);
2544     if (!Address->getType()->isPointerTy())
2545       return false;
2546     Type *AddressAccessTy = Address->getType()->getPointerElementType();
2547
2548     // Do a match against the root of this address, ignoring profitability. This
2549     // will tell us if the addressing mode for the memory operation will
2550     // *actually* cover the shared instruction.
2551     ExtAddrMode Result;
2552     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2553         TPT.getRestorationPoint();
2554     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2555                                   MemoryInst, Result, InsertedTruncs,
2556                                   PromotedInsts, TPT);
2557     Matcher.IgnoreProfitability = true;
2558     bool Success = Matcher.MatchAddr(Address, 0);
2559     (void)Success; assert(Success && "Couldn't select *anything*?");
2560
2561     // The match was to check the profitability, the changes made are not
2562     // part of the original matcher. Therefore, they should be dropped
2563     // otherwise the original matcher will not present the right state.
2564     TPT.rollback(LastKnownGood);
2565
2566     // If the match didn't cover I, then it won't be shared by it.
2567     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2568                   I) == MatchedAddrModeInsts.end())
2569       return false;
2570
2571     MatchedAddrModeInsts.clear();
2572   }
2573
2574   return true;
2575 }
2576
2577 } // end anonymous namespace
2578
2579 /// IsNonLocalValue - Return true if the specified values are defined in a
2580 /// different basic block than BB.
2581 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2582   if (Instruction *I = dyn_cast<Instruction>(V))
2583     return I->getParent() != BB;
2584   return false;
2585 }
2586
2587 /// OptimizeMemoryInst - Load and Store Instructions often have
2588 /// addressing modes that can do significant amounts of computation.  As such,
2589 /// instruction selection will try to get the load or store to do as much
2590 /// computation as possible for the program.  The problem is that isel can only
2591 /// see within a single block.  As such, we sink as much legal addressing mode
2592 /// stuff into the block as possible.
2593 ///
2594 /// This method is used to optimize both load/store and inline asms with memory
2595 /// operands.
2596 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2597                                         Type *AccessTy) {
2598   Value *Repl = Addr;
2599
2600   // Try to collapse single-value PHI nodes.  This is necessary to undo
2601   // unprofitable PRE transformations.
2602   SmallVector<Value*, 8> worklist;
2603   SmallPtrSet<Value*, 16> Visited;
2604   worklist.push_back(Addr);
2605
2606   // Use a worklist to iteratively look through PHI nodes, and ensure that
2607   // the addressing mode obtained from the non-PHI roots of the graph
2608   // are equivalent.
2609   Value *Consensus = nullptr;
2610   unsigned NumUsesConsensus = 0;
2611   bool IsNumUsesConsensusValid = false;
2612   SmallVector<Instruction*, 16> AddrModeInsts;
2613   ExtAddrMode AddrMode;
2614   TypePromotionTransaction TPT;
2615   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2616       TPT.getRestorationPoint();
2617   while (!worklist.empty()) {
2618     Value *V = worklist.back();
2619     worklist.pop_back();
2620
2621     // Break use-def graph loops.
2622     if (!Visited.insert(V).second) {
2623       Consensus = nullptr;
2624       break;
2625     }
2626
2627     // For a PHI node, push all of its incoming values.
2628     if (PHINode *P = dyn_cast<PHINode>(V)) {
2629       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2630         worklist.push_back(P->getIncomingValue(i));
2631       continue;
2632     }
2633
2634     // For non-PHIs, determine the addressing mode being computed.
2635     SmallVector<Instruction*, 16> NewAddrModeInsts;
2636     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2637         V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2638         PromotedInsts, TPT);
2639
2640     // This check is broken into two cases with very similar code to avoid using
2641     // getNumUses() as much as possible. Some values have a lot of uses, so
2642     // calling getNumUses() unconditionally caused a significant compile-time
2643     // regression.
2644     if (!Consensus) {
2645       Consensus = V;
2646       AddrMode = NewAddrMode;
2647       AddrModeInsts = NewAddrModeInsts;
2648       continue;
2649     } else if (NewAddrMode == AddrMode) {
2650       if (!IsNumUsesConsensusValid) {
2651         NumUsesConsensus = Consensus->getNumUses();
2652         IsNumUsesConsensusValid = true;
2653       }
2654
2655       // Ensure that the obtained addressing mode is equivalent to that obtained
2656       // for all other roots of the PHI traversal.  Also, when choosing one
2657       // such root as representative, select the one with the most uses in order
2658       // to keep the cost modeling heuristics in AddressingModeMatcher
2659       // applicable.
2660       unsigned NumUses = V->getNumUses();
2661       if (NumUses > NumUsesConsensus) {
2662         Consensus = V;
2663         NumUsesConsensus = NumUses;
2664         AddrModeInsts = NewAddrModeInsts;
2665       }
2666       continue;
2667     }
2668
2669     Consensus = nullptr;
2670     break;
2671   }
2672
2673   // If the addressing mode couldn't be determined, or if multiple different
2674   // ones were determined, bail out now.
2675   if (!Consensus) {
2676     TPT.rollback(LastKnownGood);
2677     return false;
2678   }
2679   TPT.commit();
2680
2681   // Check to see if any of the instructions supersumed by this addr mode are
2682   // non-local to I's BB.
2683   bool AnyNonLocal = false;
2684   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2685     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2686       AnyNonLocal = true;
2687       break;
2688     }
2689   }
2690
2691   // If all the instructions matched are already in this BB, don't do anything.
2692   if (!AnyNonLocal) {
2693     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
2694     return false;
2695   }
2696
2697   // Insert this computation right after this user.  Since our caller is
2698   // scanning from the top of the BB to the bottom, reuse of the expr are
2699   // guaranteed to happen later.
2700   IRBuilder<> Builder(MemoryInst);
2701
2702   // Now that we determined the addressing expression we want to use and know
2703   // that we have to sink it into this block.  Check to see if we have already
2704   // done this for some other load/store instr in this block.  If so, reuse the
2705   // computation.
2706   Value *&SunkAddr = SunkAddrs[Addr];
2707   if (SunkAddr) {
2708     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2709                  << *MemoryInst << "\n");
2710     if (SunkAddr->getType() != Addr->getType())
2711       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2712   } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2713                TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2714     // By default, we use the GEP-based method when AA is used later. This
2715     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2716     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2717                  << *MemoryInst << "\n");
2718     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2719     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
2720
2721     // First, find the pointer.
2722     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2723       ResultPtr = AddrMode.BaseReg;
2724       AddrMode.BaseReg = nullptr;
2725     }
2726
2727     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2728       // We can't add more than one pointer together, nor can we scale a
2729       // pointer (both of which seem meaningless).
2730       if (ResultPtr || AddrMode.Scale != 1)
2731         return false;
2732
2733       ResultPtr = AddrMode.ScaledReg;
2734       AddrMode.Scale = 0;
2735     }
2736
2737     if (AddrMode.BaseGV) {
2738       if (ResultPtr)
2739         return false;
2740
2741       ResultPtr = AddrMode.BaseGV;
2742     }
2743
2744     // If the real base value actually came from an inttoptr, then the matcher
2745     // will look through it and provide only the integer value. In that case,
2746     // use it here.
2747     if (!ResultPtr && AddrMode.BaseReg) {
2748       ResultPtr =
2749         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2750       AddrMode.BaseReg = nullptr;
2751     } else if (!ResultPtr && AddrMode.Scale == 1) {
2752       ResultPtr =
2753         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2754       AddrMode.Scale = 0;
2755     }
2756
2757     if (!ResultPtr &&
2758         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2759       SunkAddr = Constant::getNullValue(Addr->getType());
2760     } else if (!ResultPtr) {
2761       return false;
2762     } else {
2763       Type *I8PtrTy =
2764         Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2765
2766       // Start with the base register. Do this first so that subsequent address
2767       // matching finds it last, which will prevent it from trying to match it
2768       // as the scaled value in case it happens to be a mul. That would be
2769       // problematic if we've sunk a different mul for the scale, because then
2770       // we'd end up sinking both muls.
2771       if (AddrMode.BaseReg) {
2772         Value *V = AddrMode.BaseReg;
2773         if (V->getType() != IntPtrTy)
2774           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2775
2776         ResultIndex = V;
2777       }
2778
2779       // Add the scale value.
2780       if (AddrMode.Scale) {
2781         Value *V = AddrMode.ScaledReg;
2782         if (V->getType() == IntPtrTy) {
2783           // done.
2784         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2785                    cast<IntegerType>(V->getType())->getBitWidth()) {
2786           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2787         } else {
2788           // It is only safe to sign extend the BaseReg if we know that the math
2789           // required to create it did not overflow before we extend it. Since
2790           // the original IR value was tossed in favor of a constant back when
2791           // the AddrMode was created we need to bail out gracefully if widths
2792           // do not match instead of extending it.
2793           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2794           if (I && (ResultIndex != AddrMode.BaseReg))
2795             I->eraseFromParent();
2796           return false;
2797         }
2798
2799         if (AddrMode.Scale != 1)
2800           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2801                                 "sunkaddr");
2802         if (ResultIndex)
2803           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2804         else
2805           ResultIndex = V;
2806       }
2807
2808       // Add in the Base Offset if present.
2809       if (AddrMode.BaseOffs) {
2810         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2811         if (ResultIndex) {
2812           // We need to add this separately from the scale above to help with
2813           // SDAG consecutive load/store merging.
2814           if (ResultPtr->getType() != I8PtrTy)
2815             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2816           ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2817         }
2818
2819         ResultIndex = V;
2820       }
2821
2822       if (!ResultIndex) {
2823         SunkAddr = ResultPtr;
2824       } else {
2825         if (ResultPtr->getType() != I8PtrTy)
2826           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2827         SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2828       }
2829
2830       if (SunkAddr->getType() != Addr->getType())
2831         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2832     }
2833   } else {
2834     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2835                  << *MemoryInst << "\n");
2836     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2837     Value *Result = nullptr;
2838
2839     // Start with the base register. Do this first so that subsequent address
2840     // matching finds it last, which will prevent it from trying to match it
2841     // as the scaled value in case it happens to be a mul. That would be
2842     // problematic if we've sunk a different mul for the scale, because then
2843     // we'd end up sinking both muls.
2844     if (AddrMode.BaseReg) {
2845       Value *V = AddrMode.BaseReg;
2846       if (V->getType()->isPointerTy())
2847         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2848       if (V->getType() != IntPtrTy)
2849         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2850       Result = V;
2851     }
2852
2853     // Add the scale value.
2854     if (AddrMode.Scale) {
2855       Value *V = AddrMode.ScaledReg;
2856       if (V->getType() == IntPtrTy) {
2857         // done.
2858       } else if (V->getType()->isPointerTy()) {
2859         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2860       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2861                  cast<IntegerType>(V->getType())->getBitWidth()) {
2862         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2863       } else {
2864         // It is only safe to sign extend the BaseReg if we know that the math
2865         // required to create it did not overflow before we extend it. Since
2866         // the original IR value was tossed in favor of a constant back when
2867         // the AddrMode was created we need to bail out gracefully if widths
2868         // do not match instead of extending it.
2869         Instruction *I = dyn_cast_or_null<Instruction>(Result);
2870         if (I && (Result != AddrMode.BaseReg))
2871           I->eraseFromParent();
2872         return false;
2873       }
2874       if (AddrMode.Scale != 1)
2875         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2876                               "sunkaddr");
2877       if (Result)
2878         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2879       else
2880         Result = V;
2881     }
2882
2883     // Add in the BaseGV if present.
2884     if (AddrMode.BaseGV) {
2885       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2886       if (Result)
2887         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2888       else
2889         Result = V;
2890     }
2891
2892     // Add in the Base Offset if present.
2893     if (AddrMode.BaseOffs) {
2894       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2895       if (Result)
2896         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2897       else
2898         Result = V;
2899     }
2900
2901     if (!Result)
2902       SunkAddr = Constant::getNullValue(Addr->getType());
2903     else
2904       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2905   }
2906
2907   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2908
2909   // If we have no uses, recursively delete the value and all dead instructions
2910   // using it.
2911   if (Repl->use_empty()) {
2912     // This can cause recursive deletion, which can invalidate our iterator.
2913     // Use a WeakVH to hold onto it in case this happens.
2914     WeakVH IterHandle(CurInstIterator);
2915     BasicBlock *BB = CurInstIterator->getParent();
2916
2917     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2918
2919     if (IterHandle != CurInstIterator) {
2920       // If the iterator instruction was recursively deleted, start over at the
2921       // start of the block.
2922       CurInstIterator = BB->begin();
2923       SunkAddrs.clear();
2924     }
2925   }
2926   ++NumMemoryInsts;
2927   return true;
2928 }
2929
2930 /// OptimizeInlineAsmInst - If there are any memory operands, use
2931 /// OptimizeMemoryInst to sink their address computing into the block when
2932 /// possible / profitable.
2933 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2934   bool MadeChange = false;
2935
2936   TargetLowering::AsmOperandInfoVector
2937     TargetConstraints = TLI->ParseConstraints(CS);
2938   unsigned ArgNo = 0;
2939   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2940     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2941
2942     // Compute the constraint code and ConstraintType to use.
2943     TLI->ComputeConstraintToUse(OpInfo, SDValue());
2944
2945     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2946         OpInfo.isIndirect) {
2947       Value *OpVal = CS->getArgOperand(ArgNo++);
2948       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2949     } else if (OpInfo.Type == InlineAsm::isInput)
2950       ArgNo++;
2951   }
2952
2953   return MadeChange;
2954 }
2955
2956 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2957 /// basic block as the load, unless conditions are unfavorable. This allows
2958 /// SelectionDAG to fold the extend into the load.
2959 ///
2960 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2961   // Look for a load being extended.
2962   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2963   if (!LI) return false;
2964
2965   // If they're already in the same block, there's nothing to do.
2966   if (LI->getParent() == I->getParent())
2967     return false;
2968
2969   EVT VT = TLI->getValueType(I->getType());
2970   EVT LoadVT = TLI->getValueType(LI->getType());
2971
2972   // If the load has other users and the truncate is not free, this probably
2973   // isn't worthwhile.
2974   if (!LI->hasOneUse() && TLI &&
2975       (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
2976       !TLI->isTruncateFree(I->getType(), LI->getType()))
2977     return false;
2978
2979   // Check whether the target supports casts folded into loads.
2980   unsigned LType;
2981   if (isa<ZExtInst>(I))
2982     LType = ISD::ZEXTLOAD;
2983   else {
2984     assert(isa<SExtInst>(I) && "Unexpected ext type!");
2985     LType = ISD::SEXTLOAD;
2986   }
2987   if (TLI && !TLI->isLoadExtLegal(LType, LoadVT))
2988     return false;
2989
2990   // Move the extend into the same block as the load, so that SelectionDAG
2991   // can fold it.
2992   I->removeFromParent();
2993   I->insertAfter(LI);
2994   ++NumExtsMoved;
2995   return true;
2996 }
2997
2998 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2999   BasicBlock *DefBB = I->getParent();
3000
3001   // If the result of a {s|z}ext and its source are both live out, rewrite all
3002   // other uses of the source with result of extension.
3003   Value *Src = I->getOperand(0);
3004   if (Src->hasOneUse())
3005     return false;
3006
3007   // Only do this xform if truncating is free.
3008   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
3009     return false;
3010
3011   // Only safe to perform the optimization if the source is also defined in
3012   // this block.
3013   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
3014     return false;
3015
3016   bool DefIsLiveOut = false;
3017   for (User *U : I->users()) {
3018     Instruction *UI = cast<Instruction>(U);
3019
3020     // Figure out which BB this ext is used in.
3021     BasicBlock *UserBB = UI->getParent();
3022     if (UserBB == DefBB) continue;
3023     DefIsLiveOut = true;
3024     break;
3025   }
3026   if (!DefIsLiveOut)
3027     return false;
3028
3029   // Make sure none of the uses are PHI nodes.
3030   for (User *U : Src->users()) {
3031     Instruction *UI = cast<Instruction>(U);
3032     BasicBlock *UserBB = UI->getParent();
3033     if (UserBB == DefBB) continue;
3034     // Be conservative. We don't want this xform to end up introducing
3035     // reloads just before load / store instructions.
3036     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
3037       return false;
3038   }
3039
3040   // InsertedTruncs - Only insert one trunc in each block once.
3041   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3042
3043   bool MadeChange = false;
3044   for (Use &U : Src->uses()) {
3045     Instruction *User = cast<Instruction>(U.getUser());
3046
3047     // Figure out which BB this ext is used in.
3048     BasicBlock *UserBB = User->getParent();
3049     if (UserBB == DefBB) continue;
3050
3051     // Both src and def are live in this block. Rewrite the use.
3052     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3053
3054     if (!InsertedTrunc) {
3055       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3056       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3057       InsertedTruncsSet.insert(InsertedTrunc);
3058     }
3059
3060     // Replace a use of the {s|z}ext source with a use of the result.
3061     U = InsertedTrunc;
3062     ++NumExtUses;
3063     MadeChange = true;
3064   }
3065
3066   return MadeChange;
3067 }
3068
3069 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3070 /// turned into an explicit branch.
3071 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3072   // FIXME: This should use the same heuristics as IfConversion to determine
3073   // whether a select is better represented as a branch.  This requires that
3074   // branch probability metadata is preserved for the select, which is not the
3075   // case currently.
3076
3077   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3078
3079   // If the branch is predicted right, an out of order CPU can avoid blocking on
3080   // the compare.  Emit cmovs on compares with a memory operand as branches to
3081   // avoid stalls on the load from memory.  If the compare has more than one use
3082   // there's probably another cmov or setcc around so it's not worth emitting a
3083   // branch.
3084   if (!Cmp)
3085     return false;
3086
3087   Value *CmpOp0 = Cmp->getOperand(0);
3088   Value *CmpOp1 = Cmp->getOperand(1);
3089
3090   // We check that the memory operand has one use to avoid uses of the loaded
3091   // value directly after the compare, making branches unprofitable.
3092   return Cmp->hasOneUse() &&
3093          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3094           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3095 }
3096
3097
3098 /// If we have a SelectInst that will likely profit from branch prediction,
3099 /// turn it into a branch.
3100 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3101   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3102
3103   // Can we convert the 'select' to CF ?
3104   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3105     return false;
3106
3107   TargetLowering::SelectSupportKind SelectKind;
3108   if (VectorCond)
3109     SelectKind = TargetLowering::VectorMaskSelect;
3110   else if (SI->getType()->isVectorTy())
3111     SelectKind = TargetLowering::ScalarCondVectorVal;
3112   else
3113     SelectKind = TargetLowering::ScalarValSelect;
3114
3115   // Do we have efficient codegen support for this kind of 'selects' ?
3116   if (TLI->isSelectSupported(SelectKind)) {
3117     // We have efficient codegen support for the select instruction.
3118     // Check if it is profitable to keep this 'select'.
3119     if (!TLI->isPredictableSelectExpensive() ||
3120         !isFormingBranchFromSelectProfitable(SI))
3121       return false;
3122   }
3123
3124   ModifiedDT = true;
3125
3126   // First, we split the block containing the select into 2 blocks.
3127   BasicBlock *StartBlock = SI->getParent();
3128   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3129   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3130
3131   // Create a new block serving as the landing pad for the branch.
3132   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3133                                              NextBlock->getParent(), NextBlock);
3134
3135   // Move the unconditional branch from the block with the select in it into our
3136   // landing pad block.
3137   StartBlock->getTerminator()->eraseFromParent();
3138   BranchInst::Create(NextBlock, SmallBlock);
3139
3140   // Insert the real conditional branch based on the original condition.
3141   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3142
3143   // The select itself is replaced with a PHI Node.
3144   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3145   PN->takeName(SI);
3146   PN->addIncoming(SI->getTrueValue(), StartBlock);
3147   PN->addIncoming(SI->getFalseValue(), SmallBlock);
3148   SI->replaceAllUsesWith(PN);
3149   SI->eraseFromParent();
3150
3151   // Instruct OptimizeBlock to skip to the next block.
3152   CurInstIterator = StartBlock->end();
3153   ++NumSelectsExpanded;
3154   return true;
3155 }
3156
3157 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3158   SmallVector<int, 16> Mask(SVI->getShuffleMask());
3159   int SplatElem = -1;
3160   for (unsigned i = 0; i < Mask.size(); ++i) {
3161     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3162       return false;
3163     SplatElem = Mask[i];
3164   }
3165
3166   return true;
3167 }
3168
3169 /// Some targets have expensive vector shifts if the lanes aren't all the same
3170 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3171 /// it's often worth sinking a shufflevector splat down to its use so that
3172 /// codegen can spot all lanes are identical.
3173 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3174   BasicBlock *DefBB = SVI->getParent();
3175
3176   // Only do this xform if variable vector shifts are particularly expensive.
3177   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3178     return false;
3179
3180   // We only expect better codegen by sinking a shuffle if we can recognise a
3181   // constant splat.
3182   if (!isBroadcastShuffle(SVI))
3183     return false;
3184
3185   // InsertedShuffles - Only insert a shuffle in each block once.
3186   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3187
3188   bool MadeChange = false;
3189   for (User *U : SVI->users()) {
3190     Instruction *UI = cast<Instruction>(U);
3191
3192     // Figure out which BB this ext is used in.
3193     BasicBlock *UserBB = UI->getParent();
3194     if (UserBB == DefBB) continue;
3195
3196     // For now only apply this when the splat is used by a shift instruction.
3197     if (!UI->isShift()) continue;
3198
3199     // Everything checks out, sink the shuffle if the user's block doesn't
3200     // already have a copy.
3201     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3202
3203     if (!InsertedShuffle) {
3204       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3205       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3206                                               SVI->getOperand(1),
3207                                               SVI->getOperand(2), "", InsertPt);
3208     }
3209
3210     UI->replaceUsesOfWith(SVI, InsertedShuffle);
3211     MadeChange = true;
3212   }
3213
3214   // If we removed all uses, nuke the shuffle.
3215   if (SVI->use_empty()) {
3216     SVI->eraseFromParent();
3217     MadeChange = true;
3218   }
3219
3220   return MadeChange;
3221 }
3222
3223 namespace {
3224 /// \brief Helper class to promote a scalar operation to a vector one.
3225 /// This class is used to move downward extractelement transition.
3226 /// E.g.,
3227 /// a = vector_op <2 x i32>
3228 /// b = extractelement <2 x i32> a, i32 0
3229 /// c = scalar_op b
3230 /// store c
3231 ///
3232 /// =>
3233 /// a = vector_op <2 x i32>
3234 /// c = vector_op a (equivalent to scalar_op on the related lane)
3235 /// * d = extractelement <2 x i32> c, i32 0
3236 /// * store d
3237 /// Assuming both extractelement and store can be combine, we get rid of the
3238 /// transition.
3239 class VectorPromoteHelper {
3240   /// Used to perform some checks on the legality of vector operations.
3241   const TargetLowering &TLI;
3242
3243   /// Used to estimated the cost of the promoted chain.
3244   const TargetTransformInfo &TTI;
3245
3246   /// The transition being moved downwards.
3247   Instruction *Transition;
3248   /// The sequence of instructions to be promoted.
3249   SmallVector<Instruction *, 4> InstsToBePromoted;
3250   /// Cost of combining a store and an extract.
3251   unsigned StoreExtractCombineCost;
3252   /// Instruction that will be combined with the transition.
3253   Instruction *CombineInst;
3254
3255   /// \brief The instruction that represents the current end of the transition.
3256   /// Since we are faking the promotion until we reach the end of the chain
3257   /// of computation, we need a way to get the current end of the transition.
3258   Instruction *getEndOfTransition() const {
3259     if (InstsToBePromoted.empty())
3260       return Transition;
3261     return InstsToBePromoted.back();
3262   }
3263
3264   /// \brief Return the index of the original value in the transition.
3265   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3266   /// c, is at index 0.
3267   unsigned getTransitionOriginalValueIdx() const {
3268     assert(isa<ExtractElementInst>(Transition) &&
3269            "Other kind of transitions are not supported yet");
3270     return 0;
3271   }
3272
3273   /// \brief Return the index of the index in the transition.
3274   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3275   /// is at index 1.
3276   unsigned getTransitionIdx() const {
3277     assert(isa<ExtractElementInst>(Transition) &&
3278            "Other kind of transitions are not supported yet");
3279     return 1;
3280   }
3281
3282   /// \brief Get the type of the transition.
3283   /// This is the type of the original value.
3284   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3285   /// transition is <2 x i32>.
3286   Type *getTransitionType() const {
3287     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3288   }
3289
3290   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3291   /// I.e., we have the following sequence:
3292   /// Def = Transition <ty1> a to <ty2>
3293   /// b = ToBePromoted <ty2> Def, ...
3294   /// =>
3295   /// b = ToBePromoted <ty1> a, ...
3296   /// Def = Transition <ty1> ToBePromoted to <ty2>
3297   void promoteImpl(Instruction *ToBePromoted);
3298
3299   /// \brief Check whether or not it is profitable to promote all the
3300   /// instructions enqueued to be promoted.
3301   bool isProfitableToPromote() {
3302     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3303     unsigned Index = isa<ConstantInt>(ValIdx)
3304                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
3305                          : -1;
3306     Type *PromotedType = getTransitionType();
3307
3308     StoreInst *ST = cast<StoreInst>(CombineInst);
3309     unsigned AS = ST->getPointerAddressSpace();
3310     unsigned Align = ST->getAlignment();
3311     // Check if this store is supported.
3312     if (!TLI.allowsMisalignedMemoryAccesses(
3313             TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
3314       // If this is not supported, there is no way we can combine
3315       // the extract with the store.
3316       return false;
3317     }
3318
3319     // The scalar chain of computation has to pay for the transition
3320     // scalar to vector.
3321     // The vector chain has to account for the combining cost.
3322     uint64_t ScalarCost =
3323         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3324     uint64_t VectorCost = StoreExtractCombineCost;
3325     for (const auto &Inst : InstsToBePromoted) {
3326       // Compute the cost.
3327       // By construction, all instructions being promoted are arithmetic ones.
3328       // Moreover, one argument is a constant that can be viewed as a splat
3329       // constant.
3330       Value *Arg0 = Inst->getOperand(0);
3331       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3332                             isa<ConstantFP>(Arg0);
3333       TargetTransformInfo::OperandValueKind Arg0OVK =
3334           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3335                          : TargetTransformInfo::OK_AnyValue;
3336       TargetTransformInfo::OperandValueKind Arg1OVK =
3337           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3338                           : TargetTransformInfo::OK_AnyValue;
3339       ScalarCost += TTI.getArithmeticInstrCost(
3340           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3341       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3342                                                Arg0OVK, Arg1OVK);
3343     }
3344     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3345                  << ScalarCost << "\nVector: " << VectorCost << '\n');
3346     return ScalarCost > VectorCost;
3347   }
3348
3349   /// \brief Generate a constant vector with \p Val with the same
3350   /// number of elements as the transition.
3351   /// \p UseSplat defines whether or not \p Val should be replicated
3352   /// accross the whole vector.
3353   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3354   /// otherwise we generate a vector with as many undef as possible:
3355   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3356   /// used at the index of the extract.
3357   Value *getConstantVector(Constant *Val, bool UseSplat) const {
3358     unsigned ExtractIdx = UINT_MAX;
3359     if (!UseSplat) {
3360       // If we cannot determine where the constant must be, we have to
3361       // use a splat constant.
3362       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3363       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3364         ExtractIdx = CstVal->getSExtValue();
3365       else
3366         UseSplat = true;
3367     }
3368
3369     unsigned End = getTransitionType()->getVectorNumElements();
3370     if (UseSplat)
3371       return ConstantVector::getSplat(End, Val);
3372
3373     SmallVector<Constant *, 4> ConstVec;
3374     UndefValue *UndefVal = UndefValue::get(Val->getType());
3375     for (unsigned Idx = 0; Idx != End; ++Idx) {
3376       if (Idx == ExtractIdx)
3377         ConstVec.push_back(Val);
3378       else
3379         ConstVec.push_back(UndefVal);
3380     }
3381     return ConstantVector::get(ConstVec);
3382   }
3383
3384   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3385   /// in \p Use can trigger undefined behavior.
3386   static bool canCauseUndefinedBehavior(const Instruction *Use,
3387                                         unsigned OperandIdx) {
3388     // This is not safe to introduce undef when the operand is on
3389     // the right hand side of a division-like instruction.
3390     if (OperandIdx != 1)
3391       return false;
3392     switch (Use->getOpcode()) {
3393     default:
3394       return false;
3395     case Instruction::SDiv:
3396     case Instruction::UDiv:
3397     case Instruction::SRem:
3398     case Instruction::URem:
3399       return true;
3400     case Instruction::FDiv:
3401     case Instruction::FRem:
3402       return !Use->hasNoNaNs();
3403     }
3404     llvm_unreachable(nullptr);
3405   }
3406
3407 public:
3408   VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3409                       Instruction *Transition, unsigned CombineCost)
3410       : TLI(TLI), TTI(TTI), Transition(Transition),
3411         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3412     assert(Transition && "Do not know how to promote null");
3413   }
3414
3415   /// \brief Check if we can promote \p ToBePromoted to \p Type.
3416   bool canPromote(const Instruction *ToBePromoted) const {
3417     // We could support CastInst too.
3418     return isa<BinaryOperator>(ToBePromoted);
3419   }
3420
3421   /// \brief Check if it is profitable to promote \p ToBePromoted
3422   /// by moving downward the transition through.
3423   bool shouldPromote(const Instruction *ToBePromoted) const {
3424     // Promote only if all the operands can be statically expanded.
3425     // Indeed, we do not want to introduce any new kind of transitions.
3426     for (const Use &U : ToBePromoted->operands()) {
3427       const Value *Val = U.get();
3428       if (Val == getEndOfTransition()) {
3429         // If the use is a division and the transition is on the rhs,
3430         // we cannot promote the operation, otherwise we may create a
3431         // division by zero.
3432         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3433           return false;
3434         continue;
3435       }
3436       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3437           !isa<ConstantFP>(Val))
3438         return false;
3439     }
3440     // Check that the resulting operation is legal.
3441     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3442     if (!ISDOpcode)
3443       return false;
3444     return StressStoreExtract ||
3445            TLI.isOperationLegalOrCustom(
3446                ISDOpcode, TLI.getValueType(getTransitionType(), true));
3447   }
3448
3449   /// \brief Check whether or not \p Use can be combined
3450   /// with the transition.
3451   /// I.e., is it possible to do Use(Transition) => AnotherUse?
3452   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3453
3454   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3455   void enqueueForPromotion(Instruction *ToBePromoted) {
3456     InstsToBePromoted.push_back(ToBePromoted);
3457   }
3458
3459   /// \brief Set the instruction that will be combined with the transition.
3460   void recordCombineInstruction(Instruction *ToBeCombined) {
3461     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3462     CombineInst = ToBeCombined;
3463   }
3464
3465   /// \brief Promote all the instructions enqueued for promotion if it is
3466   /// is profitable.
3467   /// \return True if the promotion happened, false otherwise.
3468   bool promote() {
3469     // Check if there is something to promote.
3470     // Right now, if we do not have anything to combine with,
3471     // we assume the promotion is not profitable.
3472     if (InstsToBePromoted.empty() || !CombineInst)
3473       return false;
3474
3475     // Check cost.
3476     if (!StressStoreExtract && !isProfitableToPromote())
3477       return false;
3478
3479     // Promote.
3480     for (auto &ToBePromoted : InstsToBePromoted)
3481       promoteImpl(ToBePromoted);
3482     InstsToBePromoted.clear();
3483     return true;
3484   }
3485 };
3486 } // End of anonymous namespace.
3487
3488 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3489   // At this point, we know that all the operands of ToBePromoted but Def
3490   // can be statically promoted.
3491   // For Def, we need to use its parameter in ToBePromoted:
3492   // b = ToBePromoted ty1 a
3493   // Def = Transition ty1 b to ty2
3494   // Move the transition down.
3495   // 1. Replace all uses of the promoted operation by the transition.
3496   // = ... b => = ... Def.
3497   assert(ToBePromoted->getType() == Transition->getType() &&
3498          "The type of the result of the transition does not match "
3499          "the final type");
3500   ToBePromoted->replaceAllUsesWith(Transition);
3501   // 2. Update the type of the uses.
3502   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3503   Type *TransitionTy = getTransitionType();
3504   ToBePromoted->mutateType(TransitionTy);
3505   // 3. Update all the operands of the promoted operation with promoted
3506   // operands.
3507   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3508   for (Use &U : ToBePromoted->operands()) {
3509     Value *Val = U.get();
3510     Value *NewVal = nullptr;
3511     if (Val == Transition)
3512       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3513     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3514              isa<ConstantFP>(Val)) {
3515       // Use a splat constant if it is not safe to use undef.
3516       NewVal = getConstantVector(
3517           cast<Constant>(Val),
3518           isa<UndefValue>(Val) ||
3519               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3520     } else
3521       assert(0 && "Did you modified shouldPromote and forgot to update this?");
3522     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3523   }
3524   Transition->removeFromParent();
3525   Transition->insertAfter(ToBePromoted);
3526   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3527 }
3528
3529 /// Some targets can do store(extractelement) with one instruction.
3530 /// Try to push the extractelement towards the stores when the target
3531 /// has this feature and this is profitable.
3532 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
3533   unsigned CombineCost = UINT_MAX;
3534   if (DisableStoreExtract || !TLI ||
3535       (!StressStoreExtract &&
3536        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
3537                                        Inst->getOperand(1), CombineCost)))
3538     return false;
3539
3540   // At this point we know that Inst is a vector to scalar transition.
3541   // Try to move it down the def-use chain, until:
3542   // - We can combine the transition with its single use
3543   //   => we got rid of the transition.
3544   // - We escape the current basic block
3545   //   => we would need to check that we are moving it at a cheaper place and
3546   //      we do not do that for now.
3547   BasicBlock *Parent = Inst->getParent();
3548   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
3549   VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
3550   // If the transition has more than one use, assume this is not going to be
3551   // beneficial.
3552   while (Inst->hasOneUse()) {
3553     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
3554     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
3555
3556     if (ToBePromoted->getParent() != Parent) {
3557       DEBUG(dbgs() << "Instruction to promote is in a different block ("
3558                    << ToBePromoted->getParent()->getName()
3559                    << ") than the transition (" << Parent->getName() << ").\n");
3560       return false;
3561     }
3562
3563     if (VPH.canCombine(ToBePromoted)) {
3564       DEBUG(dbgs() << "Assume " << *Inst << '\n'
3565                    << "will be combined with: " << *ToBePromoted << '\n');
3566       VPH.recordCombineInstruction(ToBePromoted);
3567       bool Changed = VPH.promote();
3568       NumStoreExtractExposed += Changed;
3569       return Changed;
3570     }
3571
3572     DEBUG(dbgs() << "Try promoting.\n");
3573     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
3574       return false;
3575
3576     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
3577
3578     VPH.enqueueForPromotion(ToBePromoted);
3579     Inst = ToBePromoted;
3580   }
3581   return false;
3582 }
3583
3584 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
3585   if (PHINode *P = dyn_cast<PHINode>(I)) {
3586     // It is possible for very late stage optimizations (such as SimplifyCFG)
3587     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
3588     // trivial PHI, go ahead and zap it here.
3589     if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
3590                                        TLInfo, DT)) {
3591       P->replaceAllUsesWith(V);
3592       P->eraseFromParent();
3593       ++NumPHIsElim;
3594       return true;
3595     }
3596     return false;
3597   }
3598
3599   if (CastInst *CI = dyn_cast<CastInst>(I)) {
3600     // If the source of the cast is a constant, then this should have
3601     // already been constant folded.  The only reason NOT to constant fold
3602     // it is if something (e.g. LSR) was careful to place the constant
3603     // evaluation in a block other than then one that uses it (e.g. to hoist
3604     // the address of globals out of a loop).  If this is the case, we don't
3605     // want to forward-subst the cast.
3606     if (isa<Constant>(CI->getOperand(0)))
3607       return false;
3608
3609     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3610       return true;
3611
3612     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
3613       /// Sink a zext or sext into its user blocks if the target type doesn't
3614       /// fit in one register
3615       if (TLI && TLI->getTypeAction(CI->getContext(),
3616                                     TLI->getValueType(CI->getType())) ==
3617                      TargetLowering::TypeExpandInteger) {
3618         return SinkCast(CI);
3619       } else {
3620         bool MadeChange = MoveExtToFormExtLoad(I);
3621         return MadeChange | OptimizeExtUses(I);
3622       }
3623     }
3624     return false;
3625   }
3626
3627   if (CmpInst *CI = dyn_cast<CmpInst>(I))
3628     if (!TLI || !TLI->hasMultipleConditionRegisters())
3629       return OptimizeCmpExpression(CI);
3630
3631   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3632     if (TLI)
3633       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3634     return false;
3635   }
3636
3637   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3638     if (TLI)
3639       return OptimizeMemoryInst(I, SI->getOperand(1),
3640                                 SI->getOperand(0)->getType());
3641     return false;
3642   }
3643
3644   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3645
3646   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3647                 BinOp->getOpcode() == Instruction::LShr)) {
3648     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3649     if (TLI && CI && TLI->hasExtractBitsInsn())
3650       return OptimizeExtractBits(BinOp, CI, *TLI);
3651
3652     return false;
3653   }
3654
3655   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3656     if (GEPI->hasAllZeroIndices()) {
3657       /// The GEP operand must be a pointer, so must its result -> BitCast
3658       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3659                                         GEPI->getName(), GEPI);
3660       GEPI->replaceAllUsesWith(NC);
3661       GEPI->eraseFromParent();
3662       ++NumGEPsElim;
3663       OptimizeInst(NC);
3664       return true;
3665     }
3666     return false;
3667   }
3668
3669   if (CallInst *CI = dyn_cast<CallInst>(I))
3670     return OptimizeCallInst(CI);
3671
3672   if (SelectInst *SI = dyn_cast<SelectInst>(I))
3673     return OptimizeSelectInst(SI);
3674
3675   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3676     return OptimizeShuffleVectorInst(SVI);
3677
3678   if (isa<ExtractElementInst>(I))
3679     return OptimizeExtractElementInst(I);
3680
3681   return false;
3682 }
3683
3684 // In this pass we look for GEP and cast instructions that are used
3685 // across basic blocks and rewrite them to improve basic-block-at-a-time
3686 // selection.
3687 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
3688   SunkAddrs.clear();
3689   bool MadeChange = false;
3690
3691   CurInstIterator = BB.begin();
3692   while (CurInstIterator != BB.end())
3693     MadeChange |= OptimizeInst(CurInstIterator++);
3694
3695   MadeChange |= DupRetToEnableTailCallOpts(&BB);
3696
3697   return MadeChange;
3698 }
3699
3700 // llvm.dbg.value is far away from the value then iSel may not be able
3701 // handle it properly. iSel will drop llvm.dbg.value if it can not
3702 // find a node corresponding to the value.
3703 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3704   bool MadeChange = false;
3705   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3706     Instruction *PrevNonDbgInst = nullptr;
3707     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3708       Instruction *Insn = BI; ++BI;
3709       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3710       // Leave dbg.values that refer to an alloca alone. These
3711       // instrinsics describe the address of a variable (= the alloca)
3712       // being taken.  They should not be moved next to the alloca
3713       // (and to the beginning of the scope), but rather stay close to
3714       // where said address is used.
3715       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
3716         PrevNonDbgInst = Insn;
3717         continue;
3718       }
3719
3720       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3721       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3722         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3723         DVI->removeFromParent();
3724         if (isa<PHINode>(VI))
3725           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3726         else
3727           DVI->insertAfter(VI);
3728         MadeChange = true;
3729         ++NumDbgValueMoved;
3730       }
3731     }
3732   }
3733   return MadeChange;
3734 }
3735
3736 // If there is a sequence that branches based on comparing a single bit
3737 // against zero that can be combined into a single instruction, and the
3738 // target supports folding these into a single instruction, sink the
3739 // mask and compare into the branch uses. Do this before OptimizeBlock ->
3740 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3741 // searched for.
3742 bool CodeGenPrepare::sinkAndCmp(Function &F) {
3743   if (!EnableAndCmpSinking)
3744     return false;
3745   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3746     return false;
3747   bool MadeChange = false;
3748   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3749     BasicBlock *BB = I++;
3750
3751     // Does this BB end with the following?
3752     //   %andVal = and %val, #single-bit-set
3753     //   %icmpVal = icmp %andResult, 0
3754     //   br i1 %cmpVal label %dest1, label %dest2"
3755     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3756     if (!Brcc || !Brcc->isConditional())
3757       continue;
3758     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3759     if (!Cmp || Cmp->getParent() != BB)
3760       continue;
3761     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3762     if (!Zero || !Zero->isZero())
3763       continue;
3764     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3765     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3766       continue;
3767     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3768     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3769       continue;
3770     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3771
3772     // Push the "and; icmp" for any users that are conditional branches.
3773     // Since there can only be one branch use per BB, we don't need to keep
3774     // track of which BBs we insert into.
3775     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3776          UI != E; ) {
3777       Use &TheUse = *UI;
3778       // Find brcc use.
3779       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3780       ++UI;
3781       if (!BrccUser || !BrccUser->isConditional())
3782         continue;
3783       BasicBlock *UserBB = BrccUser->getParent();
3784       if (UserBB == BB) continue;
3785       DEBUG(dbgs() << "found Brcc use\n");
3786
3787       // Sink the "and; icmp" to use.
3788       MadeChange = true;
3789       BinaryOperator *NewAnd =
3790         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3791                                   BrccUser);
3792       CmpInst *NewCmp =
3793         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3794                         "", BrccUser);
3795       TheUse = NewCmp;
3796       ++NumAndCmpsMoved;
3797       DEBUG(BrccUser->getParent()->dump());
3798     }
3799   }
3800   return MadeChange;
3801 }
3802
3803 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
3804 /// success, or returns false if no or invalid metadata was found.
3805 static bool extractBranchMetadata(BranchInst *BI,
3806                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
3807   assert(BI->isConditional() &&
3808          "Looking for probabilities on unconditional branch?");
3809   auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
3810   if (!ProfileData || ProfileData->getNumOperands() != 3)
3811     return false;
3812
3813   const auto *CITrue =
3814       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
3815   const auto *CIFalse =
3816       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
3817   if (!CITrue || !CIFalse)
3818     return false;
3819
3820   ProbTrue = CITrue->getValue().getZExtValue();
3821   ProbFalse = CIFalse->getValue().getZExtValue();
3822
3823   return true;
3824 }
3825
3826 /// \brief Scale down both weights to fit into uint32_t.
3827 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
3828   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
3829   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
3830   NewTrue = NewTrue / Scale;
3831   NewFalse = NewFalse / Scale;
3832 }
3833
3834 /// \brief Some targets prefer to split a conditional branch like:
3835 /// \code
3836 ///   %0 = icmp ne i32 %a, 0
3837 ///   %1 = icmp ne i32 %b, 0
3838 ///   %or.cond = or i1 %0, %1
3839 ///   br i1 %or.cond, label %TrueBB, label %FalseBB
3840 /// \endcode
3841 /// into multiple branch instructions like:
3842 /// \code
3843 ///   bb1:
3844 ///     %0 = icmp ne i32 %a, 0
3845 ///     br i1 %0, label %TrueBB, label %bb2
3846 ///   bb2:
3847 ///     %1 = icmp ne i32 %b, 0
3848 ///     br i1 %1, label %TrueBB, label %FalseBB
3849 /// \endcode
3850 /// This usually allows instruction selection to do even further optimizations
3851 /// and combine the compare with the branch instruction. Currently this is
3852 /// applied for targets which have "cheap" jump instructions.
3853 ///
3854 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
3855 ///
3856 bool CodeGenPrepare::splitBranchCondition(Function &F) {
3857   if (!TM || TM->Options.EnableFastISel != true ||
3858       !TLI || TLI->isJumpExpensive())
3859     return false;
3860
3861   bool MadeChange = false;
3862   for (auto &BB : F) {
3863     // Does this BB end with the following?
3864     //   %cond1 = icmp|fcmp|binary instruction ...
3865     //   %cond2 = icmp|fcmp|binary instruction ...
3866     //   %cond.or = or|and i1 %cond1, cond2
3867     //   br i1 %cond.or label %dest1, label %dest2"
3868     BinaryOperator *LogicOp;
3869     BasicBlock *TBB, *FBB;
3870     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
3871       continue;
3872
3873     unsigned Opc;
3874     Value *Cond1, *Cond2;
3875     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
3876                              m_OneUse(m_Value(Cond2)))))
3877       Opc = Instruction::And;
3878     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
3879                                  m_OneUse(m_Value(Cond2)))))
3880       Opc = Instruction::Or;
3881     else
3882       continue;
3883
3884     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
3885         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
3886       continue;
3887
3888     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
3889
3890     // Create a new BB.
3891     auto *InsertBefore = std::next(Function::iterator(BB))
3892         .getNodePtrUnchecked();
3893     auto TmpBB = BasicBlock::Create(BB.getContext(),
3894                                     BB.getName() + ".cond.split",
3895                                     BB.getParent(), InsertBefore);
3896
3897     // Update original basic block by using the first condition directly by the
3898     // branch instruction and removing the no longer needed and/or instruction.
3899     auto *Br1 = cast<BranchInst>(BB.getTerminator());
3900     Br1->setCondition(Cond1);
3901     LogicOp->eraseFromParent();
3902
3903     // Depending on the conditon we have to either replace the true or the false
3904     // successor of the original branch instruction.
3905     if (Opc == Instruction::And)
3906       Br1->setSuccessor(0, TmpBB);
3907     else
3908       Br1->setSuccessor(1, TmpBB);
3909
3910     // Fill in the new basic block.
3911     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
3912     if (auto *I = dyn_cast<Instruction>(Cond2)) {
3913       I->removeFromParent();
3914       I->insertBefore(Br2);
3915     }
3916
3917     // Update PHI nodes in both successors. The original BB needs to be
3918     // replaced in one succesor's PHI nodes, because the branch comes now from
3919     // the newly generated BB (NewBB). In the other successor we need to add one
3920     // incoming edge to the PHI nodes, because both branch instructions target
3921     // now the same successor. Depending on the original branch condition
3922     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
3923     // we perfrom the correct update for the PHI nodes.
3924     // This doesn't change the successor order of the just created branch
3925     // instruction (or any other instruction).
3926     if (Opc == Instruction::Or)
3927       std::swap(TBB, FBB);
3928
3929     // Replace the old BB with the new BB.
3930     for (auto &I : *TBB) {
3931       PHINode *PN = dyn_cast<PHINode>(&I);
3932       if (!PN)
3933         break;
3934       int i;
3935       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
3936         PN->setIncomingBlock(i, TmpBB);
3937     }
3938
3939     // Add another incoming edge form the new BB.
3940     for (auto &I : *FBB) {
3941       PHINode *PN = dyn_cast<PHINode>(&I);
3942       if (!PN)
3943         break;
3944       auto *Val = PN->getIncomingValueForBlock(&BB);
3945       PN->addIncoming(Val, TmpBB);
3946     }
3947
3948     // Update the branch weights (from SelectionDAGBuilder::
3949     // FindMergedConditions).
3950     if (Opc == Instruction::Or) {
3951       // Codegen X | Y as:
3952       // BB1:
3953       //   jmp_if_X TBB
3954       //   jmp TmpBB
3955       // TmpBB:
3956       //   jmp_if_Y TBB
3957       //   jmp FBB
3958       //
3959
3960       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
3961       // The requirement is that
3962       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
3963       //     = TrueProb for orignal BB.
3964       // Assuming the orignal weights are A and B, one choice is to set BB1's
3965       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
3966       // assumes that
3967       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
3968       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
3969       // TmpBB, but the math is more complicated.
3970       uint64_t TrueWeight, FalseWeight;
3971       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
3972         uint64_t NewTrueWeight = TrueWeight;
3973         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
3974         scaleWeights(NewTrueWeight, NewFalseWeight);
3975         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
3976                          .createBranchWeights(TrueWeight, FalseWeight));
3977
3978         NewTrueWeight = TrueWeight;
3979         NewFalseWeight = 2 * FalseWeight;
3980         scaleWeights(NewTrueWeight, NewFalseWeight);
3981         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
3982                          .createBranchWeights(TrueWeight, FalseWeight));
3983       }
3984     } else {
3985       // Codegen X & Y as:
3986       // BB1:
3987       //   jmp_if_X TmpBB
3988       //   jmp FBB
3989       // TmpBB:
3990       //   jmp_if_Y TBB
3991       //   jmp FBB
3992       //
3993       //  This requires creation of TmpBB after CurBB.
3994
3995       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
3996       // The requirement is that
3997       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
3998       //     = FalseProb for orignal BB.
3999       // Assuming the orignal weights are A and B, one choice is to set BB1's
4000       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4001       // assumes that
4002       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4003       uint64_t TrueWeight, FalseWeight;
4004       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4005         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4006         uint64_t NewFalseWeight = FalseWeight;
4007         scaleWeights(NewTrueWeight, NewFalseWeight);
4008         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4009                          .createBranchWeights(TrueWeight, FalseWeight));
4010
4011         NewTrueWeight = 2 * TrueWeight;
4012         NewFalseWeight = FalseWeight;
4013         scaleWeights(NewTrueWeight, NewFalseWeight);
4014         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4015                          .createBranchWeights(TrueWeight, FalseWeight));
4016       }
4017     }
4018
4019     // Request DOM Tree update.
4020     // Note: No point in getting fancy here, since the DT info is never
4021     // available to CodeGenPrepare and the existing update code is broken
4022     // anyways.
4023     ModifiedDT = true;
4024
4025     MadeChange = true;
4026
4027     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4028           TmpBB->dump());
4029   }
4030   return MadeChange;
4031 }