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