]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/CodeGenPrepare.cpp
Merge clang trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/SetVector.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/BlockFrequencyInfo.h"
22 #include "llvm/Analysis/BranchProbabilityInfo.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/ProfileSummaryInfo.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Analysis/MemoryBuiltins.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/IR/CallSite.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GetElementPtrTypeIterator.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/InlineAsm.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/MDBuilder.h"
44 #include "llvm/IR/PatternMatch.h"
45 #include "llvm/IR/Statepoint.h"
46 #include "llvm/IR/ValueHandle.h"
47 #include "llvm/IR/ValueMap.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/BranchProbability.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetLowering.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
55 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
56 #include "llvm/Transforms/Utils/BuildLibCalls.h"
57 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
58 #include "llvm/Transforms/Utils/Cloning.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
61 #include "llvm/Transforms/Utils/ValueMapper.h"
62 using namespace llvm;
63 using namespace llvm::PatternMatch;
64
65 #define DEBUG_TYPE "codegenprepare"
66
67 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
68 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
69 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
70 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
71                       "sunken Cmps");
72 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
73                        "of sunken Casts");
74 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
75                           "computations were sunk");
76 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
77 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
78 STATISTIC(NumAndsAdded,
79           "Number of and mask instructions added to form ext loads");
80 STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
81 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
82 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
83 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
84 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
85
86 static cl::opt<bool> DisableBranchOpts(
87   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
88   cl::desc("Disable branch optimizations in CodeGenPrepare"));
89
90 static cl::opt<bool>
91     DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
92                   cl::desc("Disable GC optimizations in CodeGenPrepare"));
93
94 static cl::opt<bool> DisableSelectToBranch(
95   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
96   cl::desc("Disable select to branch conversion."));
97
98 static cl::opt<bool> AddrSinkUsingGEPs(
99   "addr-sink-using-gep", cl::Hidden, cl::init(true),
100   cl::desc("Address sinking in CGP using GEPs."));
101
102 static cl::opt<bool> EnableAndCmpSinking(
103    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
104    cl::desc("Enable sinkinig and/cmp into branches."));
105
106 static cl::opt<bool> DisableStoreExtract(
107     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
108     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
109
110 static cl::opt<bool> StressStoreExtract(
111     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
112     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
113
114 static cl::opt<bool> DisableExtLdPromotion(
115     "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
116     cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
117              "CodeGenPrepare"));
118
119 static cl::opt<bool> StressExtLdPromotion(
120     "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
121     cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
122              "optimization in CodeGenPrepare"));
123
124 static cl::opt<bool> DisablePreheaderProtect(
125     "disable-preheader-prot", cl::Hidden, cl::init(false),
126     cl::desc("Disable protection against removing loop preheaders"));
127
128 static cl::opt<bool> ProfileGuidedSectionPrefix(
129     "profile-guided-section-prefix", cl::Hidden, cl::init(true),
130     cl::desc("Use profile info to add section prefix for hot/cold functions"));
131
132 static cl::opt<unsigned> FreqRatioToSkipMerge(
133     "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
134     cl::desc("Skip merging empty blocks if (frequency of empty block) / "
135              "(frequency of destination block) is greater than this ratio"));
136
137 static cl::opt<bool> ForceSplitStore(
138     "force-split-store", cl::Hidden, cl::init(false),
139     cl::desc("Force store splitting no matter what the target query says."));
140
141 static cl::opt<bool>
142 EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
143     cl::desc("Enable merging of redundant sexts when one is dominating"
144     " the other."), cl::init(true));
145
146 namespace {
147 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
148 typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
149 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
150 typedef SmallVector<Instruction *, 16> SExts;
151 typedef DenseMap<Value *, SExts> ValueToSExts;
152 class TypePromotionTransaction;
153
154   class CodeGenPrepare : public FunctionPass {
155     const TargetMachine *TM;
156     const TargetSubtargetInfo *SubtargetInfo;
157     const TargetLowering *TLI;
158     const TargetRegisterInfo *TRI;
159     const TargetTransformInfo *TTI;
160     const TargetLibraryInfo *TLInfo;
161     const LoopInfo *LI;
162     std::unique_ptr<BlockFrequencyInfo> BFI;
163     std::unique_ptr<BranchProbabilityInfo> BPI;
164
165     /// As we scan instructions optimizing them, this is the next instruction
166     /// to optimize. Transforms that can invalidate this should update it.
167     BasicBlock::iterator CurInstIterator;
168
169     /// Keeps track of non-local addresses that have been sunk into a block.
170     /// This allows us to avoid inserting duplicate code for blocks with
171     /// multiple load/stores of the same address.
172     ValueMap<Value*, Value*> SunkAddrs;
173
174     /// Keeps track of all instructions inserted for the current function.
175     SetOfInstrs InsertedInsts;
176     /// Keeps track of the type of the related instruction before their
177     /// promotion for the current function.
178     InstrToOrigTy PromotedInsts;
179
180     /// Keep track of instructions removed during promotion.
181     SetOfInstrs RemovedInsts;
182
183     /// Keep track of sext chains based on their initial value.
184     DenseMap<Value *, Instruction *> SeenChainsForSExt;
185
186     /// Keep track of SExt promoted.
187     ValueToSExts ValToSExtendedUses;
188
189     /// True if CFG is modified in any way.
190     bool ModifiedDT;
191
192     /// True if optimizing for size.
193     bool OptSize;
194
195     /// DataLayout for the Function being processed.
196     const DataLayout *DL;
197
198   public:
199     static char ID; // Pass identification, replacement for typeid
200     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
201         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
202         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
203       }
204     bool runOnFunction(Function &F) override;
205
206     StringRef getPassName() const override { return "CodeGen Prepare"; }
207
208     void getAnalysisUsage(AnalysisUsage &AU) const override {
209       // FIXME: When we can selectively preserve passes, preserve the domtree.
210       AU.addRequired<ProfileSummaryInfoWrapperPass>();
211       AU.addRequired<TargetLibraryInfoWrapperPass>();
212       AU.addRequired<TargetTransformInfoWrapperPass>();
213       AU.addRequired<LoopInfoWrapperPass>();
214     }
215
216   private:
217     bool eliminateFallThrough(Function &F);
218     bool eliminateMostlyEmptyBlocks(Function &F);
219     BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
220     bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
221     void eliminateMostlyEmptyBlock(BasicBlock *BB);
222     bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
223                                        bool isPreheader);
224     bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
225     bool optimizeInst(Instruction *I, bool& ModifiedDT);
226     bool optimizeMemoryInst(Instruction *I, Value *Addr,
227                             Type *AccessTy, unsigned AS);
228     bool optimizeInlineAsmInst(CallInst *CS);
229     bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
230     bool optimizeExt(Instruction *&I);
231     bool optimizeExtUses(Instruction *I);
232     bool optimizeLoadExt(LoadInst *I);
233     bool optimizeSelectInst(SelectInst *SI);
234     bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
235     bool optimizeSwitchInst(SwitchInst *CI);
236     bool optimizeExtractElementInst(Instruction *Inst);
237     bool dupRetToEnableTailCallOpts(BasicBlock *BB);
238     bool placeDbgValues(Function &F);
239     bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
240                       LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
241     bool tryToPromoteExts(TypePromotionTransaction &TPT,
242                           const SmallVectorImpl<Instruction *> &Exts,
243                           SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
244                           unsigned CreatedInstsCost = 0);
245     bool mergeSExts(Function &F);
246     bool performAddressTypePromotion(
247         Instruction *&Inst,
248         bool AllowPromotionWithoutCommonHeader,
249         bool HasPromoted, TypePromotionTransaction &TPT,
250         SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
251     bool splitBranchCondition(Function &F);
252     bool simplifyOffsetableRelocate(Instruction &I);
253     bool splitIndirectCriticalEdges(Function &F);
254   };
255 }
256
257 char CodeGenPrepare::ID = 0;
258 INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
259                          "Optimize for code generation", false, false)
260 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
261 INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
262                        "Optimize for code generation", false, false)
263
264 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
265   return new CodeGenPrepare(TM);
266 }
267
268 bool CodeGenPrepare::runOnFunction(Function &F) {
269   if (skipFunction(F))
270     return false;
271
272   DL = &F.getParent()->getDataLayout();
273
274   bool EverMadeChange = false;
275   // Clear per function information.
276   InsertedInsts.clear();
277   PromotedInsts.clear();
278   BFI.reset();
279   BPI.reset();
280
281   ModifiedDT = false;
282   if (TM) {
283     SubtargetInfo = TM->getSubtargetImpl(F);
284     TLI = SubtargetInfo->getTargetLowering();
285     TRI = SubtargetInfo->getRegisterInfo();
286   }
287   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
288   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
289   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
290   OptSize = F.optForSize();
291
292   if (ProfileGuidedSectionPrefix) {
293     ProfileSummaryInfo *PSI =
294         getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
295     if (PSI->isFunctionHotInCallGraph(&F))
296       F.setSectionPrefix(".hot");
297     else if (PSI->isFunctionColdInCallGraph(&F))
298       F.setSectionPrefix(".cold");
299   }
300
301   /// This optimization identifies DIV instructions that can be
302   /// profitably bypassed and carried out with a shorter, faster divide.
303   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
304     const DenseMap<unsigned int, unsigned int> &BypassWidths =
305        TLI->getBypassSlowDivWidths();
306     BasicBlock* BB = &*F.begin();
307     while (BB != nullptr) {
308       // bypassSlowDivision may create new BBs, but we don't want to reapply the
309       // optimization to those blocks.
310       BasicBlock* Next = BB->getNextNode();
311       EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
312       BB = Next;
313     }
314   }
315
316   // Eliminate blocks that contain only PHI nodes and an
317   // unconditional branch.
318   EverMadeChange |= eliminateMostlyEmptyBlocks(F);
319
320   // llvm.dbg.value is far away from the value then iSel may not be able
321   // handle it properly. iSel will drop llvm.dbg.value if it can not
322   // find a node corresponding to the value.
323   EverMadeChange |= placeDbgValues(F);
324
325   if (!DisableBranchOpts)
326     EverMadeChange |= splitBranchCondition(F);
327
328   // Split some critical edges where one of the sources is an indirect branch,
329   // to help generate sane code for PHIs involving such edges.
330   EverMadeChange |= splitIndirectCriticalEdges(F);
331
332   bool MadeChange = true;
333   while (MadeChange) {
334     MadeChange = false;
335     SeenChainsForSExt.clear();
336     ValToSExtendedUses.clear();
337     RemovedInsts.clear();
338     for (Function::iterator I = F.begin(); I != F.end(); ) {
339       BasicBlock *BB = &*I++;
340       bool ModifiedDTOnIteration = false;
341       MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
342
343       // Restart BB iteration if the dominator tree of the Function was changed
344       if (ModifiedDTOnIteration)
345         break;
346     }
347     if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
348       MadeChange |= mergeSExts(F);
349
350     // Really free removed instructions during promotion.
351     for (Instruction *I : RemovedInsts)
352       delete I;
353
354     EverMadeChange |= MadeChange;
355   }
356
357   SunkAddrs.clear();
358
359   if (!DisableBranchOpts) {
360     MadeChange = false;
361     SmallPtrSet<BasicBlock*, 8> WorkList;
362     for (BasicBlock &BB : F) {
363       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
364       MadeChange |= ConstantFoldTerminator(&BB, true);
365       if (!MadeChange) continue;
366
367       for (SmallVectorImpl<BasicBlock*>::iterator
368              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
369         if (pred_begin(*II) == pred_end(*II))
370           WorkList.insert(*II);
371     }
372
373     // Delete the dead blocks and any of their dead successors.
374     MadeChange |= !WorkList.empty();
375     while (!WorkList.empty()) {
376       BasicBlock *BB = *WorkList.begin();
377       WorkList.erase(BB);
378       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
379
380       DeleteDeadBlock(BB);
381
382       for (SmallVectorImpl<BasicBlock*>::iterator
383              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
384         if (pred_begin(*II) == pred_end(*II))
385           WorkList.insert(*II);
386     }
387
388     // Merge pairs of basic blocks with unconditional branches, connected by
389     // a single edge.
390     if (EverMadeChange || MadeChange)
391       MadeChange |= eliminateFallThrough(F);
392
393     EverMadeChange |= MadeChange;
394   }
395
396   if (!DisableGCOpts) {
397     SmallVector<Instruction *, 2> Statepoints;
398     for (BasicBlock &BB : F)
399       for (Instruction &I : BB)
400         if (isStatepoint(I))
401           Statepoints.push_back(&I);
402     for (auto &I : Statepoints)
403       EverMadeChange |= simplifyOffsetableRelocate(*I);
404   }
405
406   return EverMadeChange;
407 }
408
409 /// Merge basic blocks which are connected by a single edge, where one of the
410 /// basic blocks has a single successor pointing to the other basic block,
411 /// which has a single predecessor.
412 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
413   bool Changed = false;
414   // Scan all of the blocks in the function, except for the entry block.
415   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
416     BasicBlock *BB = &*I++;
417     // If the destination block has a single pred, then this is a trivial
418     // edge, just collapse it.
419     BasicBlock *SinglePred = BB->getSinglePredecessor();
420
421     // Don't merge if BB's address is taken.
422     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
423
424     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
425     if (Term && !Term->isConditional()) {
426       Changed = true;
427       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
428       // Remember if SinglePred was the entry block of the function.
429       // If so, we will need to move BB back to the entry position.
430       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
431       MergeBasicBlockIntoOnlyPred(BB, nullptr);
432
433       if (isEntry && BB != &BB->getParent()->getEntryBlock())
434         BB->moveBefore(&BB->getParent()->getEntryBlock());
435
436       // We have erased a block. Update the iterator.
437       I = BB->getIterator();
438     }
439   }
440   return Changed;
441 }
442
443 /// Find a destination block from BB if BB is mergeable empty block.
444 BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
445   // If this block doesn't end with an uncond branch, ignore it.
446   BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
447   if (!BI || !BI->isUnconditional())
448     return nullptr;
449
450   // If the instruction before the branch (skipping debug info) isn't a phi
451   // node, then other stuff is happening here.
452   BasicBlock::iterator BBI = BI->getIterator();
453   if (BBI != BB->begin()) {
454     --BBI;
455     while (isa<DbgInfoIntrinsic>(BBI)) {
456       if (BBI == BB->begin())
457         break;
458       --BBI;
459     }
460     if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
461       return nullptr;
462   }
463
464   // Do not break infinite loops.
465   BasicBlock *DestBB = BI->getSuccessor(0);
466   if (DestBB == BB)
467     return nullptr;
468
469   if (!canMergeBlocks(BB, DestBB))
470     DestBB = nullptr;
471
472   return DestBB;
473 }
474
475 // Return the unique indirectbr predecessor of a block. This may return null
476 // even if such a predecessor exists, if it's not useful for splitting.
477 // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
478 // predecessors of BB.
479 static BasicBlock *
480 findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
481   // If the block doesn't have any PHIs, we don't care about it, since there's
482   // no point in splitting it.
483   PHINode *PN = dyn_cast<PHINode>(BB->begin());
484   if (!PN)
485     return nullptr;
486
487   // Verify we have exactly one IBR predecessor.
488   // Conservatively bail out if one of the other predecessors is not a "regular"
489   // terminator (that is, not a switch or a br).
490   BasicBlock *IBB = nullptr;
491   for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
492     BasicBlock *PredBB = PN->getIncomingBlock(Pred);
493     TerminatorInst *PredTerm = PredBB->getTerminator();
494     switch (PredTerm->getOpcode()) {
495     case Instruction::IndirectBr:
496       if (IBB)
497         return nullptr;
498       IBB = PredBB;
499       break;
500     case Instruction::Br:
501     case Instruction::Switch:
502       OtherPreds.push_back(PredBB);
503       continue;
504     default:
505       return nullptr;
506     }
507   }
508
509   return IBB;
510 }
511
512 // Split critical edges where the source of the edge is an indirectbr
513 // instruction. This isn't always possible, but we can handle some easy cases.
514 // This is useful because MI is unable to split such critical edges,
515 // which means it will not be able to sink instructions along those edges.
516 // This is especially painful for indirect branches with many successors, where
517 // we end up having to prepare all outgoing values in the origin block.
518 //
519 // Our normal algorithm for splitting critical edges requires us to update
520 // the outgoing edges of the edge origin block, but for an indirectbr this
521 // is hard, since it would require finding and updating the block addresses
522 // the indirect branch uses. But if a block only has a single indirectbr
523 // predecessor, with the others being regular branches, we can do it in a
524 // different way.
525 // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
526 // We can split D into D0 and D1, where D0 contains only the PHIs from D,
527 // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
528 // create the following structure:
529 // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
530 bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
531   // Check whether the function has any indirectbrs, and collect which blocks
532   // they may jump to. Since most functions don't have indirect branches,
533   // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
534   SmallSetVector<BasicBlock *, 16> Targets;
535   for (auto &BB : F) {
536     auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
537     if (!IBI)
538       continue;
539
540     for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
541       Targets.insert(IBI->getSuccessor(Succ));
542   }
543
544   if (Targets.empty())
545     return false;
546
547   bool Changed = false;
548   for (BasicBlock *Target : Targets) {
549     SmallVector<BasicBlock *, 16> OtherPreds;
550     BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
551     // If we did not found an indirectbr, or the indirectbr is the only
552     // incoming edge, this isn't the kind of edge we're looking for.
553     if (!IBRPred || OtherPreds.empty())
554       continue;
555
556     // Don't even think about ehpads/landingpads.
557     Instruction *FirstNonPHI = Target->getFirstNonPHI();
558     if (FirstNonPHI->isEHPad() || Target->isLandingPad())
559       continue;
560
561     BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
562     // It's possible Target was its own successor through an indirectbr.
563     // In this case, the indirectbr now comes from BodyBlock.
564     if (IBRPred == Target)
565       IBRPred = BodyBlock;
566
567     // At this point Target only has PHIs, and BodyBlock has the rest of the
568     // block's body. Create a copy of Target that will be used by the "direct"
569     // preds.
570     ValueToValueMapTy VMap;
571     BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
572
573     for (BasicBlock *Pred : OtherPreds)
574       Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
575
576     // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
577     // they are clones, so the number of PHIs are the same.
578     // (a) Remove the edge coming from IBRPred from the "Direct" PHI
579     // (b) Leave that as the only edge in the "Indirect" PHI.
580     // (c) Merge the two in the body block.
581     BasicBlock::iterator Indirect = Target->begin(),
582                          End = Target->getFirstNonPHI()->getIterator();
583     BasicBlock::iterator Direct = DirectSucc->begin();
584     BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
585
586     assert(&*End == Target->getTerminator() &&
587            "Block was expected to only contain PHIs");
588
589     while (Indirect != End) {
590       PHINode *DirPHI = cast<PHINode>(Direct);
591       PHINode *IndPHI = cast<PHINode>(Indirect);
592
593       // Now, clean up - the direct block shouldn't get the indirect value,
594       // and vice versa.
595       DirPHI->removeIncomingValue(IBRPred);
596       Direct++;
597
598       // Advance the pointer here, to avoid invalidation issues when the old
599       // PHI is erased.
600       Indirect++;
601
602       PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
603       NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
604                              IBRPred);
605
606       // Create a PHI in the body block, to merge the direct and indirect
607       // predecessors.
608       PHINode *MergePHI =
609           PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
610       MergePHI->addIncoming(NewIndPHI, Target);
611       MergePHI->addIncoming(DirPHI, DirectSucc);
612
613       IndPHI->replaceAllUsesWith(MergePHI);
614       IndPHI->eraseFromParent();
615     }
616
617     Changed = true;
618   }
619
620   return Changed;
621 }
622
623 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
624 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
625 /// edges in ways that are non-optimal for isel. Start by eliminating these
626 /// blocks so we can split them the way we want them.
627 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
628   SmallPtrSet<BasicBlock *, 16> Preheaders;
629   SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
630   while (!LoopList.empty()) {
631     Loop *L = LoopList.pop_back_val();
632     LoopList.insert(LoopList.end(), L->begin(), L->end());
633     if (BasicBlock *Preheader = L->getLoopPreheader())
634       Preheaders.insert(Preheader);
635   }
636
637   bool MadeChange = false;
638   // Note that this intentionally skips the entry block.
639   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
640     BasicBlock *BB = &*I++;
641     BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
642     if (!DestBB ||
643         !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
644       continue;
645
646     eliminateMostlyEmptyBlock(BB);
647     MadeChange = true;
648   }
649   return MadeChange;
650 }
651
652 bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
653                                                    BasicBlock *DestBB,
654                                                    bool isPreheader) {
655   // Do not delete loop preheaders if doing so would create a critical edge.
656   // Loop preheaders can be good locations to spill registers. If the
657   // preheader is deleted and we create a critical edge, registers may be
658   // spilled in the loop body instead.
659   if (!DisablePreheaderProtect && isPreheader &&
660       !(BB->getSinglePredecessor() &&
661         BB->getSinglePredecessor()->getSingleSuccessor()))
662     return false;
663
664   // Try to skip merging if the unique predecessor of BB is terminated by a
665   // switch or indirect branch instruction, and BB is used as an incoming block
666   // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
667   // add COPY instructions in the predecessor of BB instead of BB (if it is not
668   // merged). Note that the critical edge created by merging such blocks wont be
669   // split in MachineSink because the jump table is not analyzable. By keeping
670   // such empty block (BB), ISel will place COPY instructions in BB, not in the
671   // predecessor of BB.
672   BasicBlock *Pred = BB->getUniquePredecessor();
673   if (!Pred ||
674       !(isa<SwitchInst>(Pred->getTerminator()) ||
675         isa<IndirectBrInst>(Pred->getTerminator())))
676     return true;
677
678   if (BB->getTerminator() != BB->getFirstNonPHI())
679     return true;
680
681   // We use a simple cost heuristic which determine skipping merging is
682   // profitable if the cost of skipping merging is less than the cost of
683   // merging : Cost(skipping merging) < Cost(merging BB), where the
684   // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
685   // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
686   // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
687   //   Freq(Pred) / Freq(BB) > 2.
688   // Note that if there are multiple empty blocks sharing the same incoming
689   // value for the PHIs in the DestBB, we consider them together. In such
690   // case, Cost(merging BB) will be the sum of their frequencies.
691
692   if (!isa<PHINode>(DestBB->begin()))
693     return true;
694
695   SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
696
697   // Find all other incoming blocks from which incoming values of all PHIs in
698   // DestBB are the same as the ones from BB.
699   for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
700        ++PI) {
701     BasicBlock *DestBBPred = *PI;
702     if (DestBBPred == BB)
703       continue;
704
705     bool HasAllSameValue = true;
706     BasicBlock::const_iterator DestBBI = DestBB->begin();
707     while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
708       if (DestPN->getIncomingValueForBlock(BB) !=
709           DestPN->getIncomingValueForBlock(DestBBPred)) {
710         HasAllSameValue = false;
711         break;
712       }
713     }
714     if (HasAllSameValue)
715       SameIncomingValueBBs.insert(DestBBPred);
716   }
717
718   // See if all BB's incoming values are same as the value from Pred. In this
719   // case, no reason to skip merging because COPYs are expected to be place in
720   // Pred already.
721   if (SameIncomingValueBBs.count(Pred))
722     return true;
723
724   if (!BFI) {
725     Function &F = *BB->getParent();
726     LoopInfo LI{DominatorTree(F)};
727     BPI.reset(new BranchProbabilityInfo(F, LI));
728     BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
729   }
730
731   BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
732   BlockFrequency BBFreq = BFI->getBlockFreq(BB);
733
734   for (auto SameValueBB : SameIncomingValueBBs)
735     if (SameValueBB->getUniquePredecessor() == Pred &&
736         DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
737       BBFreq += BFI->getBlockFreq(SameValueBB);
738
739   return PredFreq.getFrequency() <=
740          BBFreq.getFrequency() * FreqRatioToSkipMerge;
741 }
742
743 /// Return true if we can merge BB into DestBB if there is a single
744 /// unconditional branch between them, and BB contains no other non-phi
745 /// instructions.
746 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
747                                     const BasicBlock *DestBB) const {
748   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
749   // the successor.  If there are more complex condition (e.g. preheaders),
750   // don't mess around with them.
751   BasicBlock::const_iterator BBI = BB->begin();
752   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
753     for (const User *U : PN->users()) {
754       const Instruction *UI = cast<Instruction>(U);
755       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
756         return false;
757       // If User is inside DestBB block and it is a PHINode then check
758       // incoming value. If incoming value is not from BB then this is
759       // a complex condition (e.g. preheaders) we want to avoid here.
760       if (UI->getParent() == DestBB) {
761         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
762           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
763             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
764             if (Insn && Insn->getParent() == BB &&
765                 Insn->getParent() != UPN->getIncomingBlock(I))
766               return false;
767           }
768       }
769     }
770   }
771
772   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
773   // and DestBB may have conflicting incoming values for the block.  If so, we
774   // can't merge the block.
775   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
776   if (!DestBBPN) return true;  // no conflict.
777
778   // Collect the preds of BB.
779   SmallPtrSet<const BasicBlock*, 16> BBPreds;
780   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
781     // It is faster to get preds from a PHI than with pred_iterator.
782     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
783       BBPreds.insert(BBPN->getIncomingBlock(i));
784   } else {
785     BBPreds.insert(pred_begin(BB), pred_end(BB));
786   }
787
788   // Walk the preds of DestBB.
789   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
790     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
791     if (BBPreds.count(Pred)) {   // Common predecessor?
792       BBI = DestBB->begin();
793       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
794         const Value *V1 = PN->getIncomingValueForBlock(Pred);
795         const Value *V2 = PN->getIncomingValueForBlock(BB);
796
797         // If V2 is a phi node in BB, look up what the mapped value will be.
798         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
799           if (V2PN->getParent() == BB)
800             V2 = V2PN->getIncomingValueForBlock(Pred);
801
802         // If there is a conflict, bail out.
803         if (V1 != V2) return false;
804       }
805     }
806   }
807
808   return true;
809 }
810
811
812 /// Eliminate a basic block that has only phi's and an unconditional branch in
813 /// it.
814 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
815   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
816   BasicBlock *DestBB = BI->getSuccessor(0);
817
818   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
819
820   // If the destination block has a single pred, then this is a trivial edge,
821   // just collapse it.
822   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
823     if (SinglePred != DestBB) {
824       // Remember if SinglePred was the entry block of the function.  If so, we
825       // will need to move BB back to the entry position.
826       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
827       MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
828
829       if (isEntry && BB != &BB->getParent()->getEntryBlock())
830         BB->moveBefore(&BB->getParent()->getEntryBlock());
831
832       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
833       return;
834     }
835   }
836
837   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
838   // to handle the new incoming edges it is about to have.
839   PHINode *PN;
840   for (BasicBlock::iterator BBI = DestBB->begin();
841        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
842     // Remove the incoming value for BB, and remember it.
843     Value *InVal = PN->removeIncomingValue(BB, false);
844
845     // Two options: either the InVal is a phi node defined in BB or it is some
846     // value that dominates BB.
847     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
848     if (InValPhi && InValPhi->getParent() == BB) {
849       // Add all of the input values of the input PHI as inputs of this phi.
850       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
851         PN->addIncoming(InValPhi->getIncomingValue(i),
852                         InValPhi->getIncomingBlock(i));
853     } else {
854       // Otherwise, add one instance of the dominating value for each edge that
855       // we will be adding.
856       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
857         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
858           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
859       } else {
860         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
861           PN->addIncoming(InVal, *PI);
862       }
863     }
864   }
865
866   // The PHIs are now updated, change everything that refers to BB to use
867   // DestBB and remove BB.
868   BB->replaceAllUsesWith(DestBB);
869   BB->eraseFromParent();
870   ++NumBlocksElim;
871
872   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
873 }
874
875 // Computes a map of base pointer relocation instructions to corresponding
876 // derived pointer relocation instructions given a vector of all relocate calls
877 static void computeBaseDerivedRelocateMap(
878     const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
879     DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
880         &RelocateInstMap) {
881   // Collect information in two maps: one primarily for locating the base object
882   // while filling the second map; the second map is the final structure holding
883   // a mapping between Base and corresponding Derived relocate calls
884   DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
885   for (auto *ThisRelocate : AllRelocateCalls) {
886     auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
887                             ThisRelocate->getDerivedPtrIndex());
888     RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
889   }
890   for (auto &Item : RelocateIdxMap) {
891     std::pair<unsigned, unsigned> Key = Item.first;
892     if (Key.first == Key.second)
893       // Base relocation: nothing to insert
894       continue;
895
896     GCRelocateInst *I = Item.second;
897     auto BaseKey = std::make_pair(Key.first, Key.first);
898
899     // We're iterating over RelocateIdxMap so we cannot modify it.
900     auto MaybeBase = RelocateIdxMap.find(BaseKey);
901     if (MaybeBase == RelocateIdxMap.end())
902       // TODO: We might want to insert a new base object relocate and gep off
903       // that, if there are enough derived object relocates.
904       continue;
905
906     RelocateInstMap[MaybeBase->second].push_back(I);
907   }
908 }
909
910 // Accepts a GEP and extracts the operands into a vector provided they're all
911 // small integer constants
912 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
913                                           SmallVectorImpl<Value *> &OffsetV) {
914   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
915     // Only accept small constant integer operands
916     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
917     if (!Op || Op->getZExtValue() > 20)
918       return false;
919   }
920
921   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
922     OffsetV.push_back(GEP->getOperand(i));
923   return true;
924 }
925
926 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
927 // replace, computes a replacement, and affects it.
928 static bool
929 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
930                           const SmallVectorImpl<GCRelocateInst *> &Targets) {
931   bool MadeChange = false;
932   for (GCRelocateInst *ToReplace : Targets) {
933     assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
934            "Not relocating a derived object of the original base object");
935     if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
936       // A duplicate relocate call. TODO: coalesce duplicates.
937       continue;
938     }
939
940     if (RelocatedBase->getParent() != ToReplace->getParent()) {
941       // Base and derived relocates are in different basic blocks.
942       // In this case transform is only valid when base dominates derived
943       // relocate. However it would be too expensive to check dominance
944       // for each such relocate, so we skip the whole transformation.
945       continue;
946     }
947
948     Value *Base = ToReplace->getBasePtr();
949     auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
950     if (!Derived || Derived->getPointerOperand() != Base)
951       continue;
952
953     SmallVector<Value *, 2> OffsetV;
954     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
955       continue;
956
957     // Create a Builder and replace the target callsite with a gep
958     assert(RelocatedBase->getNextNode() &&
959            "Should always have one since it's not a terminator");
960
961     // Insert after RelocatedBase
962     IRBuilder<> Builder(RelocatedBase->getNextNode());
963     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
964
965     // If gc_relocate does not match the actual type, cast it to the right type.
966     // In theory, there must be a bitcast after gc_relocate if the type does not
967     // match, and we should reuse it to get the derived pointer. But it could be
968     // cases like this:
969     // bb1:
970     //  ...
971     //  %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
972     //  br label %merge
973     //
974     // bb2:
975     //  ...
976     //  %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
977     //  br label %merge
978     //
979     // merge:
980     //  %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
981     //  %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
982     //
983     // In this case, we can not find the bitcast any more. So we insert a new bitcast
984     // no matter there is already one or not. In this way, we can handle all cases, and
985     // the extra bitcast should be optimized away in later passes.
986     Value *ActualRelocatedBase = RelocatedBase;
987     if (RelocatedBase->getType() != Base->getType()) {
988       ActualRelocatedBase =
989           Builder.CreateBitCast(RelocatedBase, Base->getType());
990     }
991     Value *Replacement = Builder.CreateGEP(
992         Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
993     Replacement->takeName(ToReplace);
994     // If the newly generated derived pointer's type does not match the original derived
995     // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
996     Value *ActualReplacement = Replacement;
997     if (Replacement->getType() != ToReplace->getType()) {
998       ActualReplacement =
999           Builder.CreateBitCast(Replacement, ToReplace->getType());
1000     }
1001     ToReplace->replaceAllUsesWith(ActualReplacement);
1002     ToReplace->eraseFromParent();
1003
1004     MadeChange = true;
1005   }
1006   return MadeChange;
1007 }
1008
1009 // Turns this:
1010 //
1011 // %base = ...
1012 // %ptr = gep %base + 15
1013 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1014 // %base' = relocate(%tok, i32 4, i32 4)
1015 // %ptr' = relocate(%tok, i32 4, i32 5)
1016 // %val = load %ptr'
1017 //
1018 // into this:
1019 //
1020 // %base = ...
1021 // %ptr = gep %base + 15
1022 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1023 // %base' = gc.relocate(%tok, i32 4, i32 4)
1024 // %ptr' = gep %base' + 15
1025 // %val = load %ptr'
1026 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1027   bool MadeChange = false;
1028   SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1029
1030   for (auto *U : I.users())
1031     if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1032       // Collect all the relocate calls associated with a statepoint
1033       AllRelocateCalls.push_back(Relocate);
1034
1035   // We need atleast one base pointer relocation + one derived pointer
1036   // relocation to mangle
1037   if (AllRelocateCalls.size() < 2)
1038     return false;
1039
1040   // RelocateInstMap is a mapping from the base relocate instruction to the
1041   // corresponding derived relocate instructions
1042   DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1043   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1044   if (RelocateInstMap.empty())
1045     return false;
1046
1047   for (auto &Item : RelocateInstMap)
1048     // Item.first is the RelocatedBase to offset against
1049     // Item.second is the vector of Targets to replace
1050     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1051   return MadeChange;
1052 }
1053
1054 /// SinkCast - Sink the specified cast instruction into its user blocks
1055 static bool SinkCast(CastInst *CI) {
1056   BasicBlock *DefBB = CI->getParent();
1057
1058   /// InsertedCasts - Only insert a cast in each block once.
1059   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1060
1061   bool MadeChange = false;
1062   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1063        UI != E; ) {
1064     Use &TheUse = UI.getUse();
1065     Instruction *User = cast<Instruction>(*UI);
1066
1067     // Figure out which BB this cast is used in.  For PHI's this is the
1068     // appropriate predecessor block.
1069     BasicBlock *UserBB = User->getParent();
1070     if (PHINode *PN = dyn_cast<PHINode>(User)) {
1071       UserBB = PN->getIncomingBlock(TheUse);
1072     }
1073
1074     // Preincrement use iterator so we don't invalidate it.
1075     ++UI;
1076
1077     // The first insertion point of a block containing an EH pad is after the
1078     // pad.  If the pad is the user, we cannot sink the cast past the pad.
1079     if (User->isEHPad())
1080       continue;
1081
1082     // If the block selected to receive the cast is an EH pad that does not
1083     // allow non-PHI instructions before the terminator, we can't sink the
1084     // cast.
1085     if (UserBB->getTerminator()->isEHPad())
1086       continue;
1087
1088     // If this user is in the same block as the cast, don't change the cast.
1089     if (UserBB == DefBB) continue;
1090
1091     // If we have already inserted a cast into this block, use it.
1092     CastInst *&InsertedCast = InsertedCasts[UserBB];
1093
1094     if (!InsertedCast) {
1095       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1096       assert(InsertPt != UserBB->end());
1097       InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1098                                       CI->getType(), "", &*InsertPt);
1099     }
1100
1101     // Replace a use of the cast with a use of the new cast.
1102     TheUse = InsertedCast;
1103     MadeChange = true;
1104     ++NumCastUses;
1105   }
1106
1107   // If we removed all uses, nuke the cast.
1108   if (CI->use_empty()) {
1109     CI->eraseFromParent();
1110     MadeChange = true;
1111   }
1112
1113   return MadeChange;
1114 }
1115
1116 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1117 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1118 /// reduce the number of virtual registers that must be created and coalesced.
1119 ///
1120 /// Return true if any changes are made.
1121 ///
1122 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1123                                        const DataLayout &DL) {
1124   // Sink only "cheap" (or nop) address-space casts.  This is a weaker condition
1125   // than sinking only nop casts, but is helpful on some platforms.
1126   if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1127     if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1128                                   ASC->getDestAddressSpace()))
1129       return false;
1130   }
1131
1132   // If this is a noop copy,
1133   EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1134   EVT DstVT = TLI.getValueType(DL, CI->getType());
1135
1136   // This is an fp<->int conversion?
1137   if (SrcVT.isInteger() != DstVT.isInteger())
1138     return false;
1139
1140   // If this is an extension, it will be a zero or sign extension, which
1141   // isn't a noop.
1142   if (SrcVT.bitsLT(DstVT)) return false;
1143
1144   // If these values will be promoted, find out what they will be promoted
1145   // to.  This helps us consider truncates on PPC as noop copies when they
1146   // are.
1147   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1148       TargetLowering::TypePromoteInteger)
1149     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1150   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1151       TargetLowering::TypePromoteInteger)
1152     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1153
1154   // If, after promotion, these are the same types, this is a noop copy.
1155   if (SrcVT != DstVT)
1156     return false;
1157
1158   return SinkCast(CI);
1159 }
1160
1161 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1162 /// possible.
1163 ///
1164 /// Return true if any changes were made.
1165 static bool CombineUAddWithOverflow(CmpInst *CI) {
1166   Value *A, *B;
1167   Instruction *AddI;
1168   if (!match(CI,
1169              m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1170     return false;
1171
1172   Type *Ty = AddI->getType();
1173   if (!isa<IntegerType>(Ty))
1174     return false;
1175
1176   // We don't want to move around uses of condition values this late, so we we
1177   // check if it is legal to create the call to the intrinsic in the basic
1178   // block containing the icmp:
1179
1180   if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1181     return false;
1182
1183 #ifndef NDEBUG
1184   // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1185   // for now:
1186   if (AddI->hasOneUse())
1187     assert(*AddI->user_begin() == CI && "expected!");
1188 #endif
1189
1190   Module *M = CI->getModule();
1191   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1192
1193   auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1194
1195   auto *UAddWithOverflow =
1196       CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1197   auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1198   auto *Overflow =
1199       ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1200
1201   CI->replaceAllUsesWith(Overflow);
1202   AddI->replaceAllUsesWith(UAdd);
1203   CI->eraseFromParent();
1204   AddI->eraseFromParent();
1205   return true;
1206 }
1207
1208 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1209 /// registers that must be created and coalesced. This is a clear win except on
1210 /// targets with multiple condition code registers (PowerPC), where it might
1211 /// lose; some adjustment may be wanted there.
1212 ///
1213 /// Return true if any changes are made.
1214 static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
1215   BasicBlock *DefBB = CI->getParent();
1216
1217   // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1218   if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
1219     return false;
1220
1221   // Only insert a cmp in each block once.
1222   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1223
1224   bool MadeChange = false;
1225   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1226        UI != E; ) {
1227     Use &TheUse = UI.getUse();
1228     Instruction *User = cast<Instruction>(*UI);
1229
1230     // Preincrement use iterator so we don't invalidate it.
1231     ++UI;
1232
1233     // Don't bother for PHI nodes.
1234     if (isa<PHINode>(User))
1235       continue;
1236
1237     // Figure out which BB this cmp is used in.
1238     BasicBlock *UserBB = User->getParent();
1239
1240     // If this user is in the same block as the cmp, don't change the cmp.
1241     if (UserBB == DefBB) continue;
1242
1243     // If we have already inserted a cmp into this block, use it.
1244     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1245
1246     if (!InsertedCmp) {
1247       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1248       assert(InsertPt != UserBB->end());
1249       InsertedCmp =
1250           CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1251                           CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1252       // Propagate the debug info.
1253       InsertedCmp->setDebugLoc(CI->getDebugLoc());
1254     }
1255
1256     // Replace a use of the cmp with a use of the new cmp.
1257     TheUse = InsertedCmp;
1258     MadeChange = true;
1259     ++NumCmpUses;
1260   }
1261
1262   // If we removed all uses, nuke the cmp.
1263   if (CI->use_empty()) {
1264     CI->eraseFromParent();
1265     MadeChange = true;
1266   }
1267
1268   return MadeChange;
1269 }
1270
1271 static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
1272   if (SinkCmpExpression(CI, TLI))
1273     return true;
1274
1275   if (CombineUAddWithOverflow(CI))
1276     return true;
1277
1278   return false;
1279 }
1280
1281 /// Duplicate and sink the given 'and' instruction into user blocks where it is
1282 /// used in a compare to allow isel to generate better code for targets where
1283 /// this operation can be combined.
1284 ///
1285 /// Return true if any changes are made.
1286 static bool sinkAndCmp0Expression(Instruction *AndI,
1287                                   const TargetLowering &TLI,
1288                                   SetOfInstrs &InsertedInsts) {
1289   // Double-check that we're not trying to optimize an instruction that was
1290   // already optimized by some other part of this pass.
1291   assert(!InsertedInsts.count(AndI) &&
1292          "Attempting to optimize already optimized and instruction");
1293   (void) InsertedInsts;
1294
1295   // Nothing to do for single use in same basic block.
1296   if (AndI->hasOneUse() &&
1297       AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1298     return false;
1299
1300   // Try to avoid cases where sinking/duplicating is likely to increase register
1301   // pressure.
1302   if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1303       !isa<ConstantInt>(AndI->getOperand(1)) &&
1304       AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1305     return false;
1306
1307   for (auto *U : AndI->users()) {
1308     Instruction *User = cast<Instruction>(U);
1309
1310     // Only sink for and mask feeding icmp with 0.
1311     if (!isa<ICmpInst>(User))
1312       return false;
1313
1314     auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1315     if (!CmpC || !CmpC->isZero())
1316       return false;
1317   }
1318
1319   if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1320     return false;
1321
1322   DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1323   DEBUG(AndI->getParent()->dump());
1324
1325   // Push the 'and' into the same block as the icmp 0.  There should only be
1326   // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1327   // others, so we don't need to keep track of which BBs we insert into.
1328   for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1329        UI != E; ) {
1330     Use &TheUse = UI.getUse();
1331     Instruction *User = cast<Instruction>(*UI);
1332
1333     // Preincrement use iterator so we don't invalidate it.
1334     ++UI;
1335
1336     DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1337
1338     // Keep the 'and' in the same place if the use is already in the same block.
1339     Instruction *InsertPt =
1340         User->getParent() == AndI->getParent() ? AndI : User;
1341     Instruction *InsertedAnd =
1342         BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1343                                AndI->getOperand(1), "", InsertPt);
1344     // Propagate the debug info.
1345     InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1346
1347     // Replace a use of the 'and' with a use of the new 'and'.
1348     TheUse = InsertedAnd;
1349     ++NumAndUses;
1350     DEBUG(User->getParent()->dump());
1351   }
1352
1353   // We removed all uses, nuke the and.
1354   AndI->eraseFromParent();
1355   return true;
1356 }
1357
1358 /// Check if the candidates could be combined with a shift instruction, which
1359 /// includes:
1360 /// 1. Truncate instruction
1361 /// 2. And instruction and the imm is a mask of the low bits:
1362 /// imm & (imm+1) == 0
1363 static bool isExtractBitsCandidateUse(Instruction *User) {
1364   if (!isa<TruncInst>(User)) {
1365     if (User->getOpcode() != Instruction::And ||
1366         !isa<ConstantInt>(User->getOperand(1)))
1367       return false;
1368
1369     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1370
1371     if ((Cimm & (Cimm + 1)).getBoolValue())
1372       return false;
1373   }
1374   return true;
1375 }
1376
1377 /// Sink both shift and truncate instruction to the use of truncate's BB.
1378 static bool
1379 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1380                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1381                      const TargetLowering &TLI, const DataLayout &DL) {
1382   BasicBlock *UserBB = User->getParent();
1383   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1384   TruncInst *TruncI = dyn_cast<TruncInst>(User);
1385   bool MadeChange = false;
1386
1387   for (Value::user_iterator TruncUI = TruncI->user_begin(),
1388                             TruncE = TruncI->user_end();
1389        TruncUI != TruncE;) {
1390
1391     Use &TruncTheUse = TruncUI.getUse();
1392     Instruction *TruncUser = cast<Instruction>(*TruncUI);
1393     // Preincrement use iterator so we don't invalidate it.
1394
1395     ++TruncUI;
1396
1397     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1398     if (!ISDOpcode)
1399       continue;
1400
1401     // If the use is actually a legal node, there will not be an
1402     // implicit truncate.
1403     // FIXME: always querying the result type is just an
1404     // approximation; some nodes' legality is determined by the
1405     // operand or other means. There's no good way to find out though.
1406     if (TLI.isOperationLegalOrCustom(
1407             ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1408       continue;
1409
1410     // Don't bother for PHI nodes.
1411     if (isa<PHINode>(TruncUser))
1412       continue;
1413
1414     BasicBlock *TruncUserBB = TruncUser->getParent();
1415
1416     if (UserBB == TruncUserBB)
1417       continue;
1418
1419     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1420     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1421
1422     if (!InsertedShift && !InsertedTrunc) {
1423       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1424       assert(InsertPt != TruncUserBB->end());
1425       // Sink the shift
1426       if (ShiftI->getOpcode() == Instruction::AShr)
1427         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1428                                                    "", &*InsertPt);
1429       else
1430         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1431                                                    "", &*InsertPt);
1432
1433       // Sink the trunc
1434       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1435       TruncInsertPt++;
1436       assert(TruncInsertPt != TruncUserBB->end());
1437
1438       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
1439                                        TruncI->getType(), "", &*TruncInsertPt);
1440
1441       MadeChange = true;
1442
1443       TruncTheUse = InsertedTrunc;
1444     }
1445   }
1446   return MadeChange;
1447 }
1448
1449 /// Sink the shift *right* instruction into user blocks if the uses could
1450 /// potentially be combined with this shift instruction and generate BitExtract
1451 /// instruction. It will only be applied if the architecture supports BitExtract
1452 /// instruction. Here is an example:
1453 /// BB1:
1454 ///   %x.extract.shift = lshr i64 %arg1, 32
1455 /// BB2:
1456 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
1457 /// ==>
1458 ///
1459 /// BB2:
1460 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
1461 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1462 ///
1463 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1464 /// instruction.
1465 /// Return true if any changes are made.
1466 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1467                                 const TargetLowering &TLI,
1468                                 const DataLayout &DL) {
1469   BasicBlock *DefBB = ShiftI->getParent();
1470
1471   /// Only insert instructions in each block once.
1472   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1473
1474   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1475
1476   bool MadeChange = false;
1477   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1478        UI != E;) {
1479     Use &TheUse = UI.getUse();
1480     Instruction *User = cast<Instruction>(*UI);
1481     // Preincrement use iterator so we don't invalidate it.
1482     ++UI;
1483
1484     // Don't bother for PHI nodes.
1485     if (isa<PHINode>(User))
1486       continue;
1487
1488     if (!isExtractBitsCandidateUse(User))
1489       continue;
1490
1491     BasicBlock *UserBB = User->getParent();
1492
1493     if (UserBB == DefBB) {
1494       // If the shift and truncate instruction are in the same BB. The use of
1495       // the truncate(TruncUse) may still introduce another truncate if not
1496       // legal. In this case, we would like to sink both shift and truncate
1497       // instruction to the BB of TruncUse.
1498       // for example:
1499       // BB1:
1500       // i64 shift.result = lshr i64 opnd, imm
1501       // trunc.result = trunc shift.result to i16
1502       //
1503       // BB2:
1504       //   ----> We will have an implicit truncate here if the architecture does
1505       //   not have i16 compare.
1506       // cmp i16 trunc.result, opnd2
1507       //
1508       if (isa<TruncInst>(User) && shiftIsLegal
1509           // If the type of the truncate is legal, no trucate will be
1510           // introduced in other basic blocks.
1511           &&
1512           (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1513         MadeChange =
1514             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1515
1516       continue;
1517     }
1518     // If we have already inserted a shift into this block, use it.
1519     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1520
1521     if (!InsertedShift) {
1522       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1523       assert(InsertPt != UserBB->end());
1524
1525       if (ShiftI->getOpcode() == Instruction::AShr)
1526         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1527                                                    "", &*InsertPt);
1528       else
1529         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1530                                                    "", &*InsertPt);
1531
1532       MadeChange = true;
1533     }
1534
1535     // Replace a use of the shift with a use of the new shift.
1536     TheUse = InsertedShift;
1537   }
1538
1539   // If we removed all uses, nuke the shift.
1540   if (ShiftI->use_empty())
1541     ShiftI->eraseFromParent();
1542
1543   return MadeChange;
1544 }
1545
1546 // Translate a masked load intrinsic like
1547 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1548 //                               <16 x i1> %mask, <16 x i32> %passthru)
1549 // to a chain of basic blocks, with loading element one-by-one if
1550 // the appropriate mask bit is set
1551 //
1552 //  %1 = bitcast i8* %addr to i32*
1553 //  %2 = extractelement <16 x i1> %mask, i32 0
1554 //  %3 = icmp eq i1 %2, true
1555 //  br i1 %3, label %cond.load, label %else
1556 //
1557 //cond.load:                                        ; preds = %0
1558 //  %4 = getelementptr i32* %1, i32 0
1559 //  %5 = load i32* %4
1560 //  %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1561 //  br label %else
1562 //
1563 //else:                                             ; preds = %0, %cond.load
1564 //  %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1565 //  %7 = extractelement <16 x i1> %mask, i32 1
1566 //  %8 = icmp eq i1 %7, true
1567 //  br i1 %8, label %cond.load1, label %else2
1568 //
1569 //cond.load1:                                       ; preds = %else
1570 //  %9 = getelementptr i32* %1, i32 1
1571 //  %10 = load i32* %9
1572 //  %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1573 //  br label %else2
1574 //
1575 //else2:                                            ; preds = %else, %cond.load1
1576 //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1577 //  %12 = extractelement <16 x i1> %mask, i32 2
1578 //  %13 = icmp eq i1 %12, true
1579 //  br i1 %13, label %cond.load4, label %else5
1580 //
1581 static void scalarizeMaskedLoad(CallInst *CI) {
1582   Value *Ptr  = CI->getArgOperand(0);
1583   Value *Alignment = CI->getArgOperand(1);
1584   Value *Mask = CI->getArgOperand(2);
1585   Value *Src0 = CI->getArgOperand(3);
1586
1587   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1588   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1589   assert(VecType && "Unexpected return type of masked load intrinsic");
1590
1591   Type *EltTy = CI->getType()->getVectorElementType();
1592
1593   IRBuilder<> Builder(CI->getContext());
1594   Instruction *InsertPt = CI;
1595   BasicBlock *IfBlock = CI->getParent();
1596   BasicBlock *CondBlock = nullptr;
1597   BasicBlock *PrevIfBlock = CI->getParent();
1598
1599   Builder.SetInsertPoint(InsertPt);
1600   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1601
1602   // Short-cut if the mask is all-true.
1603   bool IsAllOnesMask = isa<Constant>(Mask) &&
1604     cast<Constant>(Mask)->isAllOnesValue();
1605
1606   if (IsAllOnesMask) {
1607     Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1608     CI->replaceAllUsesWith(NewI);
1609     CI->eraseFromParent();
1610     return;
1611   }
1612
1613   // Adjust alignment for the scalar instruction.
1614   AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
1615   // Bitcast %addr fron i8* to EltTy*
1616   Type *NewPtrType =
1617     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1618   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1619   unsigned VectorWidth = VecType->getNumElements();
1620
1621   Value *UndefVal = UndefValue::get(VecType);
1622
1623   // The result vector
1624   Value *VResult = UndefVal;
1625
1626   if (isa<ConstantVector>(Mask)) {
1627     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1628       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1629           continue;
1630       Value *Gep =
1631           Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1632       LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1633       VResult = Builder.CreateInsertElement(VResult, Load,
1634                                             Builder.getInt32(Idx));
1635     }
1636     Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1637     CI->replaceAllUsesWith(NewI);
1638     CI->eraseFromParent();
1639     return;
1640   }
1641
1642   PHINode *Phi = nullptr;
1643   Value *PrevPhi = UndefVal;
1644
1645   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1646
1647     // Fill the "else" block, created in the previous iteration
1648     //
1649     //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1650     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1651     //  %to_load = icmp eq i1 %mask_1, true
1652     //  br i1 %to_load, label %cond.load, label %else
1653     //
1654     if (Idx > 0) {
1655       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1656       Phi->addIncoming(VResult, CondBlock);
1657       Phi->addIncoming(PrevPhi, PrevIfBlock);
1658       PrevPhi = Phi;
1659       VResult = Phi;
1660     }
1661
1662     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1663     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1664                                     ConstantInt::get(Predicate->getType(), 1));
1665
1666     // Create "cond" block
1667     //
1668     //  %EltAddr = getelementptr i32* %1, i32 0
1669     //  %Elt = load i32* %EltAddr
1670     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1671     //
1672     CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
1673     Builder.SetInsertPoint(InsertPt);
1674
1675     Value *Gep =
1676         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1677     LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1678     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1679
1680     // Create "else" block, fill it in the next iteration
1681     BasicBlock *NewIfBlock =
1682         CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
1683     Builder.SetInsertPoint(InsertPt);
1684     Instruction *OldBr = IfBlock->getTerminator();
1685     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1686     OldBr->eraseFromParent();
1687     PrevIfBlock = IfBlock;
1688     IfBlock = NewIfBlock;
1689   }
1690
1691   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1692   Phi->addIncoming(VResult, CondBlock);
1693   Phi->addIncoming(PrevPhi, PrevIfBlock);
1694   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1695   CI->replaceAllUsesWith(NewI);
1696   CI->eraseFromParent();
1697 }
1698
1699 // Translate a masked store intrinsic, like
1700 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1701 //                               <16 x i1> %mask)
1702 // to a chain of basic blocks, that stores element one-by-one if
1703 // the appropriate mask bit is set
1704 //
1705 //   %1 = bitcast i8* %addr to i32*
1706 //   %2 = extractelement <16 x i1> %mask, i32 0
1707 //   %3 = icmp eq i1 %2, true
1708 //   br i1 %3, label %cond.store, label %else
1709 //
1710 // cond.store:                                       ; preds = %0
1711 //   %4 = extractelement <16 x i32> %val, i32 0
1712 //   %5 = getelementptr i32* %1, i32 0
1713 //   store i32 %4, i32* %5
1714 //   br label %else
1715 //
1716 // else:                                             ; preds = %0, %cond.store
1717 //   %6 = extractelement <16 x i1> %mask, i32 1
1718 //   %7 = icmp eq i1 %6, true
1719 //   br i1 %7, label %cond.store1, label %else2
1720 //
1721 // cond.store1:                                      ; preds = %else
1722 //   %8 = extractelement <16 x i32> %val, i32 1
1723 //   %9 = getelementptr i32* %1, i32 1
1724 //   store i32 %8, i32* %9
1725 //   br label %else2
1726 //   . . .
1727 static void scalarizeMaskedStore(CallInst *CI) {
1728   Value *Src = CI->getArgOperand(0);
1729   Value *Ptr  = CI->getArgOperand(1);
1730   Value *Alignment = CI->getArgOperand(2);
1731   Value *Mask = CI->getArgOperand(3);
1732
1733   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1734   VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1735   assert(VecType && "Unexpected data type in masked store intrinsic");
1736
1737   Type *EltTy = VecType->getElementType();
1738
1739   IRBuilder<> Builder(CI->getContext());
1740   Instruction *InsertPt = CI;
1741   BasicBlock *IfBlock = CI->getParent();
1742   Builder.SetInsertPoint(InsertPt);
1743   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1744
1745   // Short-cut if the mask is all-true.
1746   bool IsAllOnesMask = isa<Constant>(Mask) &&
1747     cast<Constant>(Mask)->isAllOnesValue();
1748
1749   if (IsAllOnesMask) {
1750     Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1751     CI->eraseFromParent();
1752     return;
1753   }
1754
1755   // Adjust alignment for the scalar instruction.
1756   AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
1757   // Bitcast %addr fron i8* to EltTy*
1758   Type *NewPtrType =
1759     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1760   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1761   unsigned VectorWidth = VecType->getNumElements();
1762
1763   if (isa<ConstantVector>(Mask)) {
1764     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1765       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1766           continue;
1767       Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1768       Value *Gep =
1769           Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1770       Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1771     }
1772     CI->eraseFromParent();
1773     return;
1774   }
1775
1776   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1777
1778     // Fill the "else" block, created in the previous iteration
1779     //
1780     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1781     //  %to_store = icmp eq i1 %mask_1, true
1782     //  br i1 %to_store, label %cond.store, label %else
1783     //
1784     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1785     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1786                                     ConstantInt::get(Predicate->getType(), 1));
1787
1788     // Create "cond" block
1789     //
1790     //  %OneElt = extractelement <16 x i32> %Src, i32 Idx
1791     //  %EltAddr = getelementptr i32* %1, i32 0
1792     //  %store i32 %OneElt, i32* %EltAddr
1793     //
1794     BasicBlock *CondBlock =
1795         IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
1796     Builder.SetInsertPoint(InsertPt);
1797
1798     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1799     Value *Gep =
1800         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1801     Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1802
1803     // Create "else" block, fill it in the next iteration
1804     BasicBlock *NewIfBlock =
1805         CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
1806     Builder.SetInsertPoint(InsertPt);
1807     Instruction *OldBr = IfBlock->getTerminator();
1808     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1809     OldBr->eraseFromParent();
1810     IfBlock = NewIfBlock;
1811   }
1812   CI->eraseFromParent();
1813 }
1814
1815 // Translate a masked gather intrinsic like
1816 // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1817 //                               <16 x i1> %Mask, <16 x i32> %Src)
1818 // to a chain of basic blocks, with loading element one-by-one if
1819 // the appropriate mask bit is set
1820 //
1821 // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1822 // % Mask0 = extractelement <16 x i1> %Mask, i32 0
1823 // % ToLoad0 = icmp eq i1 % Mask0, true
1824 // br i1 % ToLoad0, label %cond.load, label %else
1825 //
1826 // cond.load:
1827 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1828 // % Load0 = load i32, i32* % Ptr0, align 4
1829 // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1830 // br label %else
1831 //
1832 // else:
1833 // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1834 // % Mask1 = extractelement <16 x i1> %Mask, i32 1
1835 // % ToLoad1 = icmp eq i1 % Mask1, true
1836 // br i1 % ToLoad1, label %cond.load1, label %else2
1837 //
1838 // cond.load1:
1839 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1840 // % Load1 = load i32, i32* % Ptr1, align 4
1841 // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1842 // br label %else2
1843 // . . .
1844 // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1845 // ret <16 x i32> %Result
1846 static void scalarizeMaskedGather(CallInst *CI) {
1847   Value *Ptrs = CI->getArgOperand(0);
1848   Value *Alignment = CI->getArgOperand(1);
1849   Value *Mask = CI->getArgOperand(2);
1850   Value *Src0 = CI->getArgOperand(3);
1851
1852   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1853
1854   assert(VecType && "Unexpected return type of masked load intrinsic");
1855
1856   IRBuilder<> Builder(CI->getContext());
1857   Instruction *InsertPt = CI;
1858   BasicBlock *IfBlock = CI->getParent();
1859   BasicBlock *CondBlock = nullptr;
1860   BasicBlock *PrevIfBlock = CI->getParent();
1861   Builder.SetInsertPoint(InsertPt);
1862   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1863
1864   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1865
1866   Value *UndefVal = UndefValue::get(VecType);
1867
1868   // The result vector
1869   Value *VResult = UndefVal;
1870   unsigned VectorWidth = VecType->getNumElements();
1871
1872   // Shorten the way if the mask is a vector of constants.
1873   bool IsConstMask = isa<ConstantVector>(Mask);
1874
1875   if (IsConstMask) {
1876     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1877       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1878         continue;
1879       Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1880                                                 "Ptr" + Twine(Idx));
1881       LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1882                                                  "Load" + Twine(Idx));
1883       VResult = Builder.CreateInsertElement(VResult, Load,
1884                                             Builder.getInt32(Idx),
1885                                             "Res" + Twine(Idx));
1886     }
1887     Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1888     CI->replaceAllUsesWith(NewI);
1889     CI->eraseFromParent();
1890     return;
1891   }
1892
1893   PHINode *Phi = nullptr;
1894   Value *PrevPhi = UndefVal;
1895
1896   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1897
1898     // Fill the "else" block, created in the previous iteration
1899     //
1900     //  %Mask1 = extractelement <16 x i1> %Mask, i32 1
1901     //  %ToLoad1 = icmp eq i1 %Mask1, true
1902     //  br i1 %ToLoad1, label %cond.load, label %else
1903     //
1904     if (Idx > 0) {
1905       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1906       Phi->addIncoming(VResult, CondBlock);
1907       Phi->addIncoming(PrevPhi, PrevIfBlock);
1908       PrevPhi = Phi;
1909       VResult = Phi;
1910     }
1911
1912     Value *Predicate = Builder.CreateExtractElement(Mask,
1913                                                     Builder.getInt32(Idx),
1914                                                     "Mask" + Twine(Idx));
1915     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1916                                     ConstantInt::get(Predicate->getType(), 1),
1917                                     "ToLoad" + Twine(Idx));
1918
1919     // Create "cond" block
1920     //
1921     //  %EltAddr = getelementptr i32* %1, i32 0
1922     //  %Elt = load i32* %EltAddr
1923     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1924     //
1925     CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1926     Builder.SetInsertPoint(InsertPt);
1927
1928     Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1929                                               "Ptr" + Twine(Idx));
1930     LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1931                                                "Load" + Twine(Idx));
1932     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1933                                           "Res" + Twine(Idx));
1934
1935     // Create "else" block, fill it in the next iteration
1936     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1937     Builder.SetInsertPoint(InsertPt);
1938     Instruction *OldBr = IfBlock->getTerminator();
1939     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1940     OldBr->eraseFromParent();
1941     PrevIfBlock = IfBlock;
1942     IfBlock = NewIfBlock;
1943   }
1944
1945   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1946   Phi->addIncoming(VResult, CondBlock);
1947   Phi->addIncoming(PrevPhi, PrevIfBlock);
1948   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1949   CI->replaceAllUsesWith(NewI);
1950   CI->eraseFromParent();
1951 }
1952
1953 // Translate a masked scatter intrinsic, like
1954 // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1955 //                                  <16 x i1> %Mask)
1956 // to a chain of basic blocks, that stores element one-by-one if
1957 // the appropriate mask bit is set.
1958 //
1959 // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1960 // % Mask0 = extractelement <16 x i1> % Mask, i32 0
1961 // % ToStore0 = icmp eq i1 % Mask0, true
1962 // br i1 %ToStore0, label %cond.store, label %else
1963 //
1964 // cond.store:
1965 // % Elt0 = extractelement <16 x i32> %Src, i32 0
1966 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1967 // store i32 %Elt0, i32* % Ptr0, align 4
1968 // br label %else
1969 //
1970 // else:
1971 // % Mask1 = extractelement <16 x i1> % Mask, i32 1
1972 // % ToStore1 = icmp eq i1 % Mask1, true
1973 // br i1 % ToStore1, label %cond.store1, label %else2
1974 //
1975 // cond.store1:
1976 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1977 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1978 // store i32 % Elt1, i32* % Ptr1, align 4
1979 // br label %else2
1980 //   . . .
1981 static void scalarizeMaskedScatter(CallInst *CI) {
1982   Value *Src = CI->getArgOperand(0);
1983   Value *Ptrs = CI->getArgOperand(1);
1984   Value *Alignment = CI->getArgOperand(2);
1985   Value *Mask = CI->getArgOperand(3);
1986
1987   assert(isa<VectorType>(Src->getType()) &&
1988          "Unexpected data type in masked scatter intrinsic");
1989   assert(isa<VectorType>(Ptrs->getType()) &&
1990          isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1991          "Vector of pointers is expected in masked scatter intrinsic");
1992
1993   IRBuilder<> Builder(CI->getContext());
1994   Instruction *InsertPt = CI;
1995   BasicBlock *IfBlock = CI->getParent();
1996   Builder.SetInsertPoint(InsertPt);
1997   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1998
1999   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2000   unsigned VectorWidth = Src->getType()->getVectorNumElements();
2001
2002   // Shorten the way if the mask is a vector of constants.
2003   bool IsConstMask = isa<ConstantVector>(Mask);
2004
2005   if (IsConstMask) {
2006     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2007       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2008         continue;
2009       Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2010                                                    "Elt" + Twine(Idx));
2011       Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2012                                                 "Ptr" + Twine(Idx));
2013       Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2014     }
2015     CI->eraseFromParent();
2016     return;
2017   }
2018   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2019     // Fill the "else" block, created in the previous iteration
2020     //
2021     //  % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
2022     //  % ToStore = icmp eq i1 % Mask1, true
2023     //  br i1 % ToStore, label %cond.store, label %else
2024     //
2025     Value *Predicate = Builder.CreateExtractElement(Mask,
2026                                                     Builder.getInt32(Idx),
2027                                                     "Mask" + Twine(Idx));
2028     Value *Cmp =
2029        Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2030                           ConstantInt::get(Predicate->getType(), 1),
2031                           "ToStore" + Twine(Idx));
2032
2033     // Create "cond" block
2034     //
2035     //  % Elt1 = extractelement <16 x i32> %Src, i32 1
2036     //  % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2037     //  %store i32 % Elt1, i32* % Ptr1
2038     //
2039     BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2040     Builder.SetInsertPoint(InsertPt);
2041
2042     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2043                                                  "Elt" + Twine(Idx));
2044     Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2045                                               "Ptr" + Twine(Idx));
2046     Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2047
2048     // Create "else" block, fill it in the next iteration
2049     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2050     Builder.SetInsertPoint(InsertPt);
2051     Instruction *OldBr = IfBlock->getTerminator();
2052     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2053     OldBr->eraseFromParent();
2054     IfBlock = NewIfBlock;
2055   }
2056   CI->eraseFromParent();
2057 }
2058
2059 /// If counting leading or trailing zeros is an expensive operation and a zero
2060 /// input is defined, add a check for zero to avoid calling the intrinsic.
2061 ///
2062 /// We want to transform:
2063 ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2064 ///
2065 /// into:
2066 ///   entry:
2067 ///     %cmpz = icmp eq i64 %A, 0
2068 ///     br i1 %cmpz, label %cond.end, label %cond.false
2069 ///   cond.false:
2070 ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2071 ///     br label %cond.end
2072 ///   cond.end:
2073 ///     %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2074 ///
2075 /// If the transform is performed, return true and set ModifiedDT to true.
2076 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2077                                   const TargetLowering *TLI,
2078                                   const DataLayout *DL,
2079                                   bool &ModifiedDT) {
2080   if (!TLI || !DL)
2081     return false;
2082
2083   // If a zero input is undefined, it doesn't make sense to despeculate that.
2084   if (match(CountZeros->getOperand(1), m_One()))
2085     return false;
2086
2087   // If it's cheap to speculate, there's nothing to do.
2088   auto IntrinsicID = CountZeros->getIntrinsicID();
2089   if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2090       (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2091     return false;
2092
2093   // Only handle legal scalar cases. Anything else requires too much work.
2094   Type *Ty = CountZeros->getType();
2095   unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
2096   if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
2097     return false;
2098
2099   // The intrinsic will be sunk behind a compare against zero and branch.
2100   BasicBlock *StartBlock = CountZeros->getParent();
2101   BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2102
2103   // Create another block after the count zero intrinsic. A PHI will be added
2104   // in this block to select the result of the intrinsic or the bit-width
2105   // constant if the input to the intrinsic is zero.
2106   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2107   BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2108
2109   // Set up a builder to create a compare, conditional branch, and PHI.
2110   IRBuilder<> Builder(CountZeros->getContext());
2111   Builder.SetInsertPoint(StartBlock->getTerminator());
2112   Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2113
2114   // Replace the unconditional branch that was created by the first split with
2115   // a compare against zero and a conditional branch.
2116   Value *Zero = Constant::getNullValue(Ty);
2117   Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2118   Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2119   StartBlock->getTerminator()->eraseFromParent();
2120
2121   // Create a PHI in the end block to select either the output of the intrinsic
2122   // or the bit width of the operand.
2123   Builder.SetInsertPoint(&EndBlock->front());
2124   PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2125   CountZeros->replaceAllUsesWith(PN);
2126   Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2127   PN->addIncoming(BitWidth, StartBlock);
2128   PN->addIncoming(CountZeros, CallBlock);
2129
2130   // We are explicitly handling the zero case, so we can set the intrinsic's
2131   // undefined zero argument to 'true'. This will also prevent reprocessing the
2132   // intrinsic; we only despeculate when a zero input is defined.
2133   CountZeros->setArgOperand(1, Builder.getTrue());
2134   ModifiedDT = true;
2135   return true;
2136 }
2137
2138 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
2139   BasicBlock *BB = CI->getParent();
2140
2141   // Lower inline assembly if we can.
2142   // If we found an inline asm expession, and if the target knows how to
2143   // lower it to normal LLVM code, do so now.
2144   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2145     if (TLI->ExpandInlineAsm(CI)) {
2146       // Avoid invalidating the iterator.
2147       CurInstIterator = BB->begin();
2148       // Avoid processing instructions out of order, which could cause
2149       // reuse before a value is defined.
2150       SunkAddrs.clear();
2151       return true;
2152     }
2153     // Sink address computing for memory operands into the block.
2154     if (optimizeInlineAsmInst(CI))
2155       return true;
2156   }
2157
2158   // Align the pointer arguments to this call if the target thinks it's a good
2159   // idea
2160   unsigned MinSize, PrefAlign;
2161   if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2162     for (auto &Arg : CI->arg_operands()) {
2163       // We want to align both objects whose address is used directly and
2164       // objects whose address is used in casts and GEPs, though it only makes
2165       // sense for GEPs if the offset is a multiple of the desired alignment and
2166       // if size - offset meets the size threshold.
2167       if (!Arg->getType()->isPointerTy())
2168         continue;
2169       APInt Offset(DL->getPointerSizeInBits(
2170                        cast<PointerType>(Arg->getType())->getAddressSpace()),
2171                    0);
2172       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2173       uint64_t Offset2 = Offset.getLimitedValue();
2174       if ((Offset2 & (PrefAlign-1)) != 0)
2175         continue;
2176       AllocaInst *AI;
2177       if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2178           DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2179         AI->setAlignment(PrefAlign);
2180       // Global variables can only be aligned if they are defined in this
2181       // object (i.e. they are uniquely initialized in this object), and
2182       // over-aligning global variables that have an explicit section is
2183       // forbidden.
2184       GlobalVariable *GV;
2185       if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2186           GV->getPointerAlignment(*DL) < PrefAlign &&
2187           DL->getTypeAllocSize(GV->getValueType()) >=
2188               MinSize + Offset2)
2189         GV->setAlignment(PrefAlign);
2190     }
2191     // If this is a memcpy (or similar) then we may be able to improve the
2192     // alignment
2193     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2194       unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2195       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2196         Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2197       if (Align > MI->getAlignment())
2198         MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2199     }
2200   }
2201
2202   // If we have a cold call site, try to sink addressing computation into the
2203   // cold block.  This interacts with our handling for loads and stores to
2204   // ensure that we can fold all uses of a potential addressing computation
2205   // into their uses.  TODO: generalize this to work over profiling data
2206   if (!OptSize && CI->hasFnAttr(Attribute::Cold))
2207     for (auto &Arg : CI->arg_operands()) {
2208       if (!Arg->getType()->isPointerTy())
2209         continue;
2210       unsigned AS = Arg->getType()->getPointerAddressSpace();
2211       return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2212     }
2213
2214   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2215   if (II) {
2216     switch (II->getIntrinsicID()) {
2217     default: break;
2218     case Intrinsic::objectsize: {
2219       // Lower all uses of llvm.objectsize.*
2220       ConstantInt *RetVal =
2221           lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
2222       // Substituting this can cause recursive simplifications, which can
2223       // invalidate our iterator.  Use a WeakVH to hold onto it in case this
2224       // happens.
2225       Value *CurValue = &*CurInstIterator;
2226       WeakVH IterHandle(CurValue);
2227
2228       replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2229
2230       // If the iterator instruction was recursively deleted, start over at the
2231       // start of the block.
2232       if (IterHandle != CurValue) {
2233         CurInstIterator = BB->begin();
2234         SunkAddrs.clear();
2235       }
2236       return true;
2237     }
2238     case Intrinsic::masked_load: {
2239       // Scalarize unsupported vector masked load
2240       if (!TTI->isLegalMaskedLoad(CI->getType())) {
2241         scalarizeMaskedLoad(CI);
2242         ModifiedDT = true;
2243         return true;
2244       }
2245       return false;
2246     }
2247     case Intrinsic::masked_store: {
2248       if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
2249         scalarizeMaskedStore(CI);
2250         ModifiedDT = true;
2251         return true;
2252       }
2253       return false;
2254     }
2255     case Intrinsic::masked_gather: {
2256       if (!TTI->isLegalMaskedGather(CI->getType())) {
2257         scalarizeMaskedGather(CI);
2258         ModifiedDT = true;
2259         return true;
2260       }
2261       return false;
2262     }
2263     case Intrinsic::masked_scatter: {
2264       if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
2265         scalarizeMaskedScatter(CI);
2266         ModifiedDT = true;
2267         return true;
2268       }
2269       return false;
2270     }
2271     case Intrinsic::aarch64_stlxr:
2272     case Intrinsic::aarch64_stxr: {
2273       ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2274       if (!ExtVal || !ExtVal->hasOneUse() ||
2275           ExtVal->getParent() == CI->getParent())
2276         return false;
2277       // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2278       ExtVal->moveBefore(CI);
2279       // Mark this instruction as "inserted by CGP", so that other
2280       // optimizations don't touch it.
2281       InsertedInsts.insert(ExtVal);
2282       return true;
2283     }
2284     case Intrinsic::invariant_group_barrier:
2285       II->replaceAllUsesWith(II->getArgOperand(0));
2286       II->eraseFromParent();
2287       return true;
2288
2289     case Intrinsic::cttz:
2290     case Intrinsic::ctlz:
2291       // If counting zeros is expensive, try to avoid it.
2292       return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2293     }
2294
2295     if (TLI) {
2296       SmallVector<Value*, 2> PtrOps;
2297       Type *AccessTy;
2298       if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2299         while (!PtrOps.empty()) {
2300           Value *PtrVal = PtrOps.pop_back_val();
2301           unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2302           if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2303             return true;
2304         }
2305     }
2306   }
2307
2308   // From here on out we're working with named functions.
2309   if (!CI->getCalledFunction()) return false;
2310
2311   // Lower all default uses of _chk calls.  This is very similar
2312   // to what InstCombineCalls does, but here we are only lowering calls
2313   // to fortified library functions (e.g. __memcpy_chk) that have the default
2314   // "don't know" as the objectsize.  Anything else should be left alone.
2315   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2316   if (Value *V = Simplifier.optimizeCall(CI)) {
2317     CI->replaceAllUsesWith(V);
2318     CI->eraseFromParent();
2319     return true;
2320   }
2321   return false;
2322 }
2323
2324 /// Look for opportunities to duplicate return instructions to the predecessor
2325 /// to enable tail call optimizations. The case it is currently looking for is:
2326 /// @code
2327 /// bb0:
2328 ///   %tmp0 = tail call i32 @f0()
2329 ///   br label %return
2330 /// bb1:
2331 ///   %tmp1 = tail call i32 @f1()
2332 ///   br label %return
2333 /// bb2:
2334 ///   %tmp2 = tail call i32 @f2()
2335 ///   br label %return
2336 /// return:
2337 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2338 ///   ret i32 %retval
2339 /// @endcode
2340 ///
2341 /// =>
2342 ///
2343 /// @code
2344 /// bb0:
2345 ///   %tmp0 = tail call i32 @f0()
2346 ///   ret i32 %tmp0
2347 /// bb1:
2348 ///   %tmp1 = tail call i32 @f1()
2349 ///   ret i32 %tmp1
2350 /// bb2:
2351 ///   %tmp2 = tail call i32 @f2()
2352 ///   ret i32 %tmp2
2353 /// @endcode
2354 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
2355   if (!TLI)
2356     return false;
2357
2358   ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2359   if (!RetI)
2360     return false;
2361
2362   PHINode *PN = nullptr;
2363   BitCastInst *BCI = nullptr;
2364   Value *V = RetI->getReturnValue();
2365   if (V) {
2366     BCI = dyn_cast<BitCastInst>(V);
2367     if (BCI)
2368       V = BCI->getOperand(0);
2369
2370     PN = dyn_cast<PHINode>(V);
2371     if (!PN)
2372       return false;
2373   }
2374
2375   if (PN && PN->getParent() != BB)
2376     return false;
2377
2378   // Make sure there are no instructions between the PHI and return, or that the
2379   // return is the first instruction in the block.
2380   if (PN) {
2381     BasicBlock::iterator BI = BB->begin();
2382     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
2383     if (&*BI == BCI)
2384       // Also skip over the bitcast.
2385       ++BI;
2386     if (&*BI != RetI)
2387       return false;
2388   } else {
2389     BasicBlock::iterator BI = BB->begin();
2390     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2391     if (&*BI != RetI)
2392       return false;
2393   }
2394
2395   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2396   /// call.
2397   const Function *F = BB->getParent();
2398   SmallVector<CallInst*, 4> TailCalls;
2399   if (PN) {
2400     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2401       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2402       // Make sure the phi value is indeed produced by the tail call.
2403       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2404           TLI->mayBeEmittedAsTailCall(CI) &&
2405           attributesPermitTailCall(F, CI, RetI, *TLI))
2406         TailCalls.push_back(CI);
2407     }
2408   } else {
2409     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
2410     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
2411       if (!VisitedBBs.insert(*PI).second)
2412         continue;
2413
2414       BasicBlock::InstListType &InstList = (*PI)->getInstList();
2415       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2416       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
2417       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2418       if (RI == RE)
2419         continue;
2420
2421       CallInst *CI = dyn_cast<CallInst>(&*RI);
2422       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2423           attributesPermitTailCall(F, CI, RetI, *TLI))
2424         TailCalls.push_back(CI);
2425     }
2426   }
2427
2428   bool Changed = false;
2429   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2430     CallInst *CI = TailCalls[i];
2431     CallSite CS(CI);
2432
2433     // Conservatively require the attributes of the call to match those of the
2434     // return. Ignore noalias because it doesn't affect the call sequence.
2435     AttributeList CalleeAttrs = CS.getAttributes();
2436     if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2437             .removeAttribute(Attribute::NoAlias) !=
2438         AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2439             .removeAttribute(Attribute::NoAlias))
2440       continue;
2441
2442     // Make sure the call instruction is followed by an unconditional branch to
2443     // the return block.
2444     BasicBlock *CallBB = CI->getParent();
2445     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2446     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2447       continue;
2448
2449     // Duplicate the return into CallBB.
2450     (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
2451     ModifiedDT = Changed = true;
2452     ++NumRetsDup;
2453   }
2454
2455   // If we eliminated all predecessors of the block, delete the block now.
2456   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
2457     BB->eraseFromParent();
2458
2459   return Changed;
2460 }
2461
2462 //===----------------------------------------------------------------------===//
2463 // Memory Optimization
2464 //===----------------------------------------------------------------------===//
2465
2466 namespace {
2467
2468 /// This is an extended version of TargetLowering::AddrMode
2469 /// which holds actual Value*'s for register values.
2470 struct ExtAddrMode : public TargetLowering::AddrMode {
2471   Value *BaseReg;
2472   Value *ScaledReg;
2473   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
2474   void print(raw_ostream &OS) const;
2475   void dump() const;
2476
2477   bool operator==(const ExtAddrMode& O) const {
2478     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2479            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2480            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2481   }
2482 };
2483
2484 #ifndef NDEBUG
2485 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2486   AM.print(OS);
2487   return OS;
2488 }
2489 #endif
2490
2491 void ExtAddrMode::print(raw_ostream &OS) const {
2492   bool NeedPlus = false;
2493   OS << "[";
2494   if (BaseGV) {
2495     OS << (NeedPlus ? " + " : "")
2496        << "GV:";
2497     BaseGV->printAsOperand(OS, /*PrintType=*/false);
2498     NeedPlus = true;
2499   }
2500
2501   if (BaseOffs) {
2502     OS << (NeedPlus ? " + " : "")
2503        << BaseOffs;
2504     NeedPlus = true;
2505   }
2506
2507   if (BaseReg) {
2508     OS << (NeedPlus ? " + " : "")
2509        << "Base:";
2510     BaseReg->printAsOperand(OS, /*PrintType=*/false);
2511     NeedPlus = true;
2512   }
2513   if (Scale) {
2514     OS << (NeedPlus ? " + " : "")
2515        << Scale << "*";
2516     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2517   }
2518
2519   OS << ']';
2520 }
2521
2522 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2523 LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
2524   print(dbgs());
2525   dbgs() << '\n';
2526 }
2527 #endif
2528
2529 /// \brief This class provides transaction based operation on the IR.
2530 /// Every change made through this class is recorded in the internal state and
2531 /// can be undone (rollback) until commit is called.
2532 class TypePromotionTransaction {
2533
2534   /// \brief This represents the common interface of the individual transaction.
2535   /// Each class implements the logic for doing one specific modification on
2536   /// the IR via the TypePromotionTransaction.
2537   class TypePromotionAction {
2538   protected:
2539     /// The Instruction modified.
2540     Instruction *Inst;
2541
2542   public:
2543     /// \brief Constructor of the action.
2544     /// The constructor performs the related action on the IR.
2545     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2546
2547     virtual ~TypePromotionAction() {}
2548
2549     /// \brief Undo the modification done by this action.
2550     /// When this method is called, the IR must be in the same state as it was
2551     /// before this action was applied.
2552     /// \pre Undoing the action works if and only if the IR is in the exact same
2553     /// state as it was directly after this action was applied.
2554     virtual void undo() = 0;
2555
2556     /// \brief Advocate every change made by this action.
2557     /// When the results on the IR of the action are to be kept, it is important
2558     /// to call this function, otherwise hidden information may be kept forever.
2559     virtual void commit() {
2560       // Nothing to be done, this action is not doing anything.
2561     }
2562   };
2563
2564   /// \brief Utility to remember the position of an instruction.
2565   class InsertionHandler {
2566     /// Position of an instruction.
2567     /// Either an instruction:
2568     /// - Is the first in a basic block: BB is used.
2569     /// - Has a previous instructon: PrevInst is used.
2570     union {
2571       Instruction *PrevInst;
2572       BasicBlock *BB;
2573     } Point;
2574     /// Remember whether or not the instruction had a previous instruction.
2575     bool HasPrevInstruction;
2576
2577   public:
2578     /// \brief Record the position of \p Inst.
2579     InsertionHandler(Instruction *Inst) {
2580       BasicBlock::iterator It = Inst->getIterator();
2581       HasPrevInstruction = (It != (Inst->getParent()->begin()));
2582       if (HasPrevInstruction)
2583         Point.PrevInst = &*--It;
2584       else
2585         Point.BB = Inst->getParent();
2586     }
2587
2588     /// \brief Insert \p Inst at the recorded position.
2589     void insert(Instruction *Inst) {
2590       if (HasPrevInstruction) {
2591         if (Inst->getParent())
2592           Inst->removeFromParent();
2593         Inst->insertAfter(Point.PrevInst);
2594       } else {
2595         Instruction *Position = &*Point.BB->getFirstInsertionPt();
2596         if (Inst->getParent())
2597           Inst->moveBefore(Position);
2598         else
2599           Inst->insertBefore(Position);
2600       }
2601     }
2602   };
2603
2604   /// \brief Move an instruction before another.
2605   class InstructionMoveBefore : public TypePromotionAction {
2606     /// Original position of the instruction.
2607     InsertionHandler Position;
2608
2609   public:
2610     /// \brief Move \p Inst before \p Before.
2611     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2612         : TypePromotionAction(Inst), Position(Inst) {
2613       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2614       Inst->moveBefore(Before);
2615     }
2616
2617     /// \brief Move the instruction back to its original position.
2618     void undo() override {
2619       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2620       Position.insert(Inst);
2621     }
2622   };
2623
2624   /// \brief Set the operand of an instruction with a new value.
2625   class OperandSetter : public TypePromotionAction {
2626     /// Original operand of the instruction.
2627     Value *Origin;
2628     /// Index of the modified instruction.
2629     unsigned Idx;
2630
2631   public:
2632     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2633     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2634         : TypePromotionAction(Inst), Idx(Idx) {
2635       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2636                    << "for:" << *Inst << "\n"
2637                    << "with:" << *NewVal << "\n");
2638       Origin = Inst->getOperand(Idx);
2639       Inst->setOperand(Idx, NewVal);
2640     }
2641
2642     /// \brief Restore the original value of the instruction.
2643     void undo() override {
2644       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2645                    << "for: " << *Inst << "\n"
2646                    << "with: " << *Origin << "\n");
2647       Inst->setOperand(Idx, Origin);
2648     }
2649   };
2650
2651   /// \brief Hide the operands of an instruction.
2652   /// Do as if this instruction was not using any of its operands.
2653   class OperandsHider : public TypePromotionAction {
2654     /// The list of original operands.
2655     SmallVector<Value *, 4> OriginalValues;
2656
2657   public:
2658     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2659     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2660       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2661       unsigned NumOpnds = Inst->getNumOperands();
2662       OriginalValues.reserve(NumOpnds);
2663       for (unsigned It = 0; It < NumOpnds; ++It) {
2664         // Save the current operand.
2665         Value *Val = Inst->getOperand(It);
2666         OriginalValues.push_back(Val);
2667         // Set a dummy one.
2668         // We could use OperandSetter here, but that would imply an overhead
2669         // that we are not willing to pay.
2670         Inst->setOperand(It, UndefValue::get(Val->getType()));
2671       }
2672     }
2673
2674     /// \brief Restore the original list of uses.
2675     void undo() override {
2676       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2677       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2678         Inst->setOperand(It, OriginalValues[It]);
2679     }
2680   };
2681
2682   /// \brief Build a truncate instruction.
2683   class TruncBuilder : public TypePromotionAction {
2684     Value *Val;
2685   public:
2686     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2687     /// result.
2688     /// trunc Opnd to Ty.
2689     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2690       IRBuilder<> Builder(Opnd);
2691       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2692       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
2693     }
2694
2695     /// \brief Get the built value.
2696     Value *getBuiltValue() { return Val; }
2697
2698     /// \brief Remove the built instruction.
2699     void undo() override {
2700       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2701       if (Instruction *IVal = dyn_cast<Instruction>(Val))
2702         IVal->eraseFromParent();
2703     }
2704   };
2705
2706   /// \brief Build a sign extension instruction.
2707   class SExtBuilder : public TypePromotionAction {
2708     Value *Val;
2709   public:
2710     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2711     /// result.
2712     /// sext Opnd to Ty.
2713     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2714         : TypePromotionAction(InsertPt) {
2715       IRBuilder<> Builder(InsertPt);
2716       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2717       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
2718     }
2719
2720     /// \brief Get the built value.
2721     Value *getBuiltValue() { return Val; }
2722
2723     /// \brief Remove the built instruction.
2724     void undo() override {
2725       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2726       if (Instruction *IVal = dyn_cast<Instruction>(Val))
2727         IVal->eraseFromParent();
2728     }
2729   };
2730
2731   /// \brief Build a zero extension instruction.
2732   class ZExtBuilder : public TypePromotionAction {
2733     Value *Val;
2734   public:
2735     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2736     /// result.
2737     /// zext Opnd to Ty.
2738     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2739         : TypePromotionAction(InsertPt) {
2740       IRBuilder<> Builder(InsertPt);
2741       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2742       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
2743     }
2744
2745     /// \brief Get the built value.
2746     Value *getBuiltValue() { return Val; }
2747
2748     /// \brief Remove the built instruction.
2749     void undo() override {
2750       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2751       if (Instruction *IVal = dyn_cast<Instruction>(Val))
2752         IVal->eraseFromParent();
2753     }
2754   };
2755
2756   /// \brief Mutate an instruction to another type.
2757   class TypeMutator : public TypePromotionAction {
2758     /// Record the original type.
2759     Type *OrigTy;
2760
2761   public:
2762     /// \brief Mutate the type of \p Inst into \p NewTy.
2763     TypeMutator(Instruction *Inst, Type *NewTy)
2764         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2765       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2766                    << "\n");
2767       Inst->mutateType(NewTy);
2768     }
2769
2770     /// \brief Mutate the instruction back to its original type.
2771     void undo() override {
2772       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2773                    << "\n");
2774       Inst->mutateType(OrigTy);
2775     }
2776   };
2777
2778   /// \brief Replace the uses of an instruction by another instruction.
2779   class UsesReplacer : public TypePromotionAction {
2780     /// Helper structure to keep track of the replaced uses.
2781     struct InstructionAndIdx {
2782       /// The instruction using the instruction.
2783       Instruction *Inst;
2784       /// The index where this instruction is used for Inst.
2785       unsigned Idx;
2786       InstructionAndIdx(Instruction *Inst, unsigned Idx)
2787           : Inst(Inst), Idx(Idx) {}
2788     };
2789
2790     /// Keep track of the original uses (pair Instruction, Index).
2791     SmallVector<InstructionAndIdx, 4> OriginalUses;
2792     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2793
2794   public:
2795     /// \brief Replace all the use of \p Inst by \p New.
2796     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2797       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2798                    << "\n");
2799       // Record the original uses.
2800       for (Use &U : Inst->uses()) {
2801         Instruction *UserI = cast<Instruction>(U.getUser());
2802         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2803       }
2804       // Now, we can replace the uses.
2805       Inst->replaceAllUsesWith(New);
2806     }
2807
2808     /// \brief Reassign the original uses of Inst to Inst.
2809     void undo() override {
2810       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2811       for (use_iterator UseIt = OriginalUses.begin(),
2812                         EndIt = OriginalUses.end();
2813            UseIt != EndIt; ++UseIt) {
2814         UseIt->Inst->setOperand(UseIt->Idx, Inst);
2815       }
2816     }
2817   };
2818
2819   /// \brief Remove an instruction from the IR.
2820   class InstructionRemover : public TypePromotionAction {
2821     /// Original position of the instruction.
2822     InsertionHandler Inserter;
2823     /// Helper structure to hide all the link to the instruction. In other
2824     /// words, this helps to do as if the instruction was removed.
2825     OperandsHider Hider;
2826     /// Keep track of the uses replaced, if any.
2827     UsesReplacer *Replacer;
2828     /// Keep track of instructions removed.
2829     SetOfInstrs &RemovedInsts;
2830
2831   public:
2832     /// \brief Remove all reference of \p Inst and optinally replace all its
2833     /// uses with New.
2834     /// \p RemovedInsts Keep track of the instructions removed by this Action.
2835     /// \pre If !Inst->use_empty(), then New != nullptr
2836     InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2837                        Value *New = nullptr)
2838         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
2839           Replacer(nullptr), RemovedInsts(RemovedInsts) {
2840       if (New)
2841         Replacer = new UsesReplacer(Inst, New);
2842       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2843       RemovedInsts.insert(Inst);
2844       /// The instructions removed here will be freed after completing
2845       /// optimizeBlock() for all blocks as we need to keep track of the
2846       /// removed instructions during promotion.
2847       Inst->removeFromParent();
2848     }
2849
2850     ~InstructionRemover() override { delete Replacer; }
2851
2852     /// \brief Resurrect the instruction and reassign it to the proper uses if
2853     /// new value was provided when build this action.
2854     void undo() override {
2855       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2856       Inserter.insert(Inst);
2857       if (Replacer)
2858         Replacer->undo();
2859       Hider.undo();
2860       RemovedInsts.erase(Inst);
2861     }
2862   };
2863
2864 public:
2865   /// Restoration point.
2866   /// The restoration point is a pointer to an action instead of an iterator
2867   /// because the iterator may be invalidated but not the pointer.
2868   typedef const TypePromotionAction *ConstRestorationPt;
2869
2870   TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2871       : RemovedInsts(RemovedInsts) {}
2872
2873   /// Advocate every changes made in that transaction.
2874   void commit();
2875   /// Undo all the changes made after the given point.
2876   void rollback(ConstRestorationPt Point);
2877   /// Get the current restoration point.
2878   ConstRestorationPt getRestorationPoint() const;
2879
2880   /// \name API for IR modification with state keeping to support rollback.
2881   /// @{
2882   /// Same as Instruction::setOperand.
2883   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2884   /// Same as Instruction::eraseFromParent.
2885   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
2886   /// Same as Value::replaceAllUsesWith.
2887   void replaceAllUsesWith(Instruction *Inst, Value *New);
2888   /// Same as Value::mutateType.
2889   void mutateType(Instruction *Inst, Type *NewTy);
2890   /// Same as IRBuilder::createTrunc.
2891   Value *createTrunc(Instruction *Opnd, Type *Ty);
2892   /// Same as IRBuilder::createSExt.
2893   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
2894   /// Same as IRBuilder::createZExt.
2895   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
2896   /// Same as Instruction::moveBefore.
2897   void moveBefore(Instruction *Inst, Instruction *Before);
2898   /// @}
2899
2900 private:
2901   /// The ordered list of actions made so far.
2902   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2903   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
2904   SetOfInstrs &RemovedInsts;
2905 };
2906
2907 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2908                                           Value *NewVal) {
2909   Actions.push_back(
2910       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
2911 }
2912
2913 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2914                                                 Value *NewVal) {
2915   Actions.push_back(
2916       make_unique<TypePromotionTransaction::InstructionRemover>(Inst,
2917                                                          RemovedInsts, NewVal));
2918 }
2919
2920 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2921                                                   Value *New) {
2922   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
2923 }
2924
2925 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
2926   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
2927 }
2928
2929 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2930                                              Type *Ty) {
2931   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
2932   Value *Val = Ptr->getBuiltValue();
2933   Actions.push_back(std::move(Ptr));
2934   return Val;
2935 }
2936
2937 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2938                                             Value *Opnd, Type *Ty) {
2939   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
2940   Value *Val = Ptr->getBuiltValue();
2941   Actions.push_back(std::move(Ptr));
2942   return Val;
2943 }
2944
2945 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2946                                             Value *Opnd, Type *Ty) {
2947   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
2948   Value *Val = Ptr->getBuiltValue();
2949   Actions.push_back(std::move(Ptr));
2950   return Val;
2951 }
2952
2953 void TypePromotionTransaction::moveBefore(Instruction *Inst,
2954                                           Instruction *Before) {
2955   Actions.push_back(
2956       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
2957 }
2958
2959 TypePromotionTransaction::ConstRestorationPt
2960 TypePromotionTransaction::getRestorationPoint() const {
2961   return !Actions.empty() ? Actions.back().get() : nullptr;
2962 }
2963
2964 void TypePromotionTransaction::commit() {
2965   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
2966        ++It)
2967     (*It)->commit();
2968   Actions.clear();
2969 }
2970
2971 void TypePromotionTransaction::rollback(
2972     TypePromotionTransaction::ConstRestorationPt Point) {
2973   while (!Actions.empty() && Point != Actions.back().get()) {
2974     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
2975     Curr->undo();
2976   }
2977 }
2978
2979 /// \brief A helper class for matching addressing modes.
2980 ///
2981 /// This encapsulates the logic for matching the target-legal addressing modes.
2982 class AddressingModeMatcher {
2983   SmallVectorImpl<Instruction*> &AddrModeInsts;
2984   const TargetLowering &TLI;
2985   const TargetRegisterInfo &TRI;
2986   const DataLayout &DL;
2987
2988   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2989   /// the memory instruction that we're computing this address for.
2990   Type *AccessTy;
2991   unsigned AddrSpace;
2992   Instruction *MemoryInst;
2993
2994   /// This is the addressing mode that we're building up. This is
2995   /// part of the return value of this addressing mode matching stuff.
2996   ExtAddrMode &AddrMode;
2997
2998   /// The instructions inserted by other CodeGenPrepare optimizations.
2999   const SetOfInstrs &InsertedInsts;
3000   /// A map from the instructions to their type before promotion.
3001   InstrToOrigTy &PromotedInsts;
3002   /// The ongoing transaction where every action should be registered.
3003   TypePromotionTransaction &TPT;
3004
3005   /// This is set to true when we should not do profitability checks.
3006   /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3007   bool IgnoreProfitability;
3008
3009   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
3010                         const TargetLowering &TLI,
3011                         const TargetRegisterInfo &TRI,
3012                         Type *AT, unsigned AS,
3013                         Instruction *MI, ExtAddrMode &AM,
3014                         const SetOfInstrs &InsertedInsts,
3015                         InstrToOrigTy &PromotedInsts,
3016                         TypePromotionTransaction &TPT)
3017       : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3018         DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3019         MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3020         PromotedInsts(PromotedInsts), TPT(TPT) {
3021     IgnoreProfitability = false;
3022   }
3023 public:
3024
3025   /// Find the maximal addressing mode that a load/store of V can fold,
3026   /// give an access type of AccessTy.  This returns a list of involved
3027   /// instructions in AddrModeInsts.
3028   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3029   /// optimizations.
3030   /// \p PromotedInsts maps the instructions to their type before promotion.
3031   /// \p The ongoing transaction where every action should be registered.
3032   static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
3033                            Instruction *MemoryInst,
3034                            SmallVectorImpl<Instruction*> &AddrModeInsts,
3035                            const TargetLowering &TLI,
3036                            const TargetRegisterInfo &TRI,
3037                            const SetOfInstrs &InsertedInsts,
3038                            InstrToOrigTy &PromotedInsts,
3039                            TypePromotionTransaction &TPT) {
3040     ExtAddrMode Result;
3041
3042     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
3043                                          AccessTy, AS,
3044                                          MemoryInst, Result, InsertedInsts,
3045                                          PromotedInsts, TPT).matchAddr(V, 0);
3046     (void)Success; assert(Success && "Couldn't select *anything*?");
3047     return Result;
3048   }
3049 private:
3050   bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3051   bool matchAddr(Value *V, unsigned Depth);
3052   bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
3053                           bool *MovedAway = nullptr);
3054   bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3055                                             ExtAddrMode &AMBefore,
3056                                             ExtAddrMode &AMAfter);
3057   bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3058   bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3059                              Value *PromotedOperand) const;
3060 };
3061
3062 /// Try adding ScaleReg*Scale to the current addressing mode.
3063 /// Return true and update AddrMode if this addr mode is legal for the target,
3064 /// false if not.
3065 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3066                                              unsigned Depth) {
3067   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3068   // mode.  Just process that directly.
3069   if (Scale == 1)
3070     return matchAddr(ScaleReg, Depth);
3071
3072   // If the scale is 0, it takes nothing to add this.
3073   if (Scale == 0)
3074     return true;
3075
3076   // If we already have a scale of this value, we can add to it, otherwise, we
3077   // need an available scale field.
3078   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3079     return false;
3080
3081   ExtAddrMode TestAddrMode = AddrMode;
3082
3083   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
3084   // [A+B + A*7] -> [B+A*8].
3085   TestAddrMode.Scale += Scale;
3086   TestAddrMode.ScaledReg = ScaleReg;
3087
3088   // If the new address isn't legal, bail out.
3089   if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3090     return false;
3091
3092   // It was legal, so commit it.
3093   AddrMode = TestAddrMode;
3094
3095   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
3096   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
3097   // X*Scale + C*Scale to addr mode.
3098   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3099   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
3100       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3101     TestAddrMode.ScaledReg = AddLHS;
3102     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
3103
3104     // If this addressing mode is legal, commit it and remember that we folded
3105     // this instruction.
3106     if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3107       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3108       AddrMode = TestAddrMode;
3109       return true;
3110     }
3111   }
3112
3113   // Otherwise, not (x+c)*scale, just return what we have.
3114   return true;
3115 }
3116
3117 /// This is a little filter, which returns true if an addressing computation
3118 /// involving I might be folded into a load/store accessing it.
3119 /// This doesn't need to be perfect, but needs to accept at least
3120 /// the set of instructions that MatchOperationAddr can.
3121 static bool MightBeFoldableInst(Instruction *I) {
3122   switch (I->getOpcode()) {
3123   case Instruction::BitCast:
3124   case Instruction::AddrSpaceCast:
3125     // Don't touch identity bitcasts.
3126     if (I->getType() == I->getOperand(0)->getType())
3127       return false;
3128     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3129   case Instruction::PtrToInt:
3130     // PtrToInt is always a noop, as we know that the int type is pointer sized.
3131     return true;
3132   case Instruction::IntToPtr:
3133     // We know the input is intptr_t, so this is foldable.
3134     return true;
3135   case Instruction::Add:
3136     return true;
3137   case Instruction::Mul:
3138   case Instruction::Shl:
3139     // Can only handle X*C and X << C.
3140     return isa<ConstantInt>(I->getOperand(1));
3141   case Instruction::GetElementPtr:
3142     return true;
3143   default:
3144     return false;
3145   }
3146 }
3147
3148 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3149 /// \note \p Val is assumed to be the product of some type promotion.
3150 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3151 /// to be legal, as the non-promoted value would have had the same state.
3152 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3153                                        const DataLayout &DL, Value *Val) {
3154   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3155   if (!PromotedInst)
3156     return false;
3157   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3158   // If the ISDOpcode is undefined, it was undefined before the promotion.
3159   if (!ISDOpcode)
3160     return true;
3161   // Otherwise, check if the promoted instruction is legal or not.
3162   return TLI.isOperationLegalOrCustom(
3163       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
3164 }
3165
3166 /// \brief Hepler class to perform type promotion.
3167 class TypePromotionHelper {
3168   /// \brief Utility function to check whether or not a sign or zero extension
3169   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3170   /// either using the operands of \p Inst or promoting \p Inst.
3171   /// The type of the extension is defined by \p IsSExt.
3172   /// In other words, check if:
3173   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
3174   /// #1 Promotion applies:
3175   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
3176   /// #2 Operand reuses:
3177   /// ext opnd1 to ConsideredExtType.
3178   /// \p PromotedInsts maps the instructions to their type before promotion.
3179   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3180                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
3181
3182   /// \brief Utility function to determine if \p OpIdx should be promoted when
3183   /// promoting \p Inst.
3184   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
3185     return !(isa<SelectInst>(Inst) && OpIdx == 0);
3186   }
3187
3188   /// \brief Utility function to promote the operand of \p Ext when this
3189   /// operand is a promotable trunc or sext or zext.
3190   /// \p PromotedInsts maps the instructions to their type before promotion.
3191   /// \p CreatedInstsCost[out] contains the cost of all instructions
3192   /// created to promote the operand of Ext.
3193   /// Newly added extensions are inserted in \p Exts.
3194   /// Newly added truncates are inserted in \p Truncs.
3195   /// Should never be called directly.
3196   /// \return The promoted value which is used instead of Ext.
3197   static Value *promoteOperandForTruncAndAnyExt(
3198       Instruction *Ext, TypePromotionTransaction &TPT,
3199       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3200       SmallVectorImpl<Instruction *> *Exts,
3201       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
3202
3203   /// \brief Utility function to promote the operand of \p Ext when this
3204   /// operand is promotable and is not a supported trunc or sext.
3205   /// \p PromotedInsts maps the instructions to their type before promotion.
3206   /// \p CreatedInstsCost[out] contains the cost of all the instructions
3207   /// created to promote the operand of Ext.
3208   /// Newly added extensions are inserted in \p Exts.
3209   /// Newly added truncates are inserted in \p Truncs.
3210   /// Should never be called directly.
3211   /// \return The promoted value which is used instead of Ext.
3212   static Value *promoteOperandForOther(Instruction *Ext,
3213                                        TypePromotionTransaction &TPT,
3214                                        InstrToOrigTy &PromotedInsts,
3215                                        unsigned &CreatedInstsCost,
3216                                        SmallVectorImpl<Instruction *> *Exts,
3217                                        SmallVectorImpl<Instruction *> *Truncs,
3218                                        const TargetLowering &TLI, bool IsSExt);
3219
3220   /// \see promoteOperandForOther.
3221   static Value *signExtendOperandForOther(
3222       Instruction *Ext, TypePromotionTransaction &TPT,
3223       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3224       SmallVectorImpl<Instruction *> *Exts,
3225       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3226     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3227                                   Exts, Truncs, TLI, true);
3228   }
3229
3230   /// \see promoteOperandForOther.
3231   static Value *zeroExtendOperandForOther(
3232       Instruction *Ext, TypePromotionTransaction &TPT,
3233       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3234       SmallVectorImpl<Instruction *> *Exts,
3235       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3236     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3237                                   Exts, Truncs, TLI, false);
3238   }
3239
3240 public:
3241   /// Type for the utility function that promotes the operand of Ext.
3242   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
3243                            InstrToOrigTy &PromotedInsts,
3244                            unsigned &CreatedInstsCost,
3245                            SmallVectorImpl<Instruction *> *Exts,
3246                            SmallVectorImpl<Instruction *> *Truncs,
3247                            const TargetLowering &TLI);
3248   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3249   /// action to promote the operand of \p Ext instead of using Ext.
3250   /// \return NULL if no promotable action is possible with the current
3251   /// sign extension.
3252   /// \p InsertedInsts keeps track of all the instructions inserted by the
3253   /// other CodeGenPrepare optimizations. This information is important
3254   /// because we do not want to promote these instructions as CodeGenPrepare
3255   /// will reinsert them later. Thus creating an infinite loop: create/remove.
3256   /// \p PromotedInsts maps the instructions to their type before promotion.
3257   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
3258                           const TargetLowering &TLI,
3259                           const InstrToOrigTy &PromotedInsts);
3260 };
3261
3262 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
3263                                         Type *ConsideredExtType,
3264                                         const InstrToOrigTy &PromotedInsts,
3265                                         bool IsSExt) {
3266   // The promotion helper does not know how to deal with vector types yet.
3267   // To be able to fix that, we would need to fix the places where we
3268   // statically extend, e.g., constants and such.
3269   if (Inst->getType()->isVectorTy())
3270     return false;
3271
3272   // We can always get through zext.
3273   if (isa<ZExtInst>(Inst))
3274     return true;
3275
3276   // sext(sext) is ok too.
3277   if (IsSExt && isa<SExtInst>(Inst))
3278     return true;
3279
3280   // We can get through binary operator, if it is legal. In other words, the
3281   // binary operator must have a nuw or nsw flag.
3282   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3283   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3284       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3285        (IsSExt && BinOp->hasNoSignedWrap())))
3286     return true;
3287
3288   // Check if we can do the following simplification.
3289   // ext(trunc(opnd)) --> ext(opnd)
3290   if (!isa<TruncInst>(Inst))
3291     return false;
3292
3293   Value *OpndVal = Inst->getOperand(0);
3294   // Check if we can use this operand in the extension.
3295   // If the type is larger than the result type of the extension, we cannot.
3296   if (!OpndVal->getType()->isIntegerTy() ||
3297       OpndVal->getType()->getIntegerBitWidth() >
3298           ConsideredExtType->getIntegerBitWidth())
3299     return false;
3300
3301   // If the operand of the truncate is not an instruction, we will not have
3302   // any information on the dropped bits.
3303   // (Actually we could for constant but it is not worth the extra logic).
3304   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3305   if (!Opnd)
3306     return false;
3307
3308   // Check if the source of the type is narrow enough.
3309   // I.e., check that trunc just drops extended bits of the same kind of
3310   // the extension.
3311   // #1 get the type of the operand and check the kind of the extended bits.
3312   const Type *OpndType;
3313   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3314   if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3315     OpndType = It->second.getPointer();
3316   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3317     OpndType = Opnd->getOperand(0)->getType();
3318   else
3319     return false;
3320
3321   // #2 check that the truncate just drops extended bits.
3322   return Inst->getType()->getIntegerBitWidth() >=
3323          OpndType->getIntegerBitWidth();
3324 }
3325
3326 TypePromotionHelper::Action TypePromotionHelper::getAction(
3327     Instruction *Ext, const SetOfInstrs &InsertedInsts,
3328     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3329   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3330          "Unexpected instruction type");
3331   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3332   Type *ExtTy = Ext->getType();
3333   bool IsSExt = isa<SExtInst>(Ext);
3334   // If the operand of the extension is not an instruction, we cannot
3335   // get through.
3336   // If it, check we can get through.
3337   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3338     return nullptr;
3339
3340   // Do not promote if the operand has been added by codegenprepare.
3341   // Otherwise, it means we are undoing an optimization that is likely to be
3342   // redone, thus causing potential infinite loop.
3343   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3344     return nullptr;
3345
3346   // SExt or Trunc instructions.
3347   // Return the related handler.
3348   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3349       isa<ZExtInst>(ExtOpnd))
3350     return promoteOperandForTruncAndAnyExt;
3351
3352   // Regular instruction.
3353   // Abort early if we will have to insert non-free instructions.
3354   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
3355     return nullptr;
3356   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3357 }
3358
3359 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3360     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
3361     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3362     SmallVectorImpl<Instruction *> *Exts,
3363     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3364   // By construction, the operand of SExt is an instruction. Otherwise we cannot
3365   // get through it and this method should not be called.
3366   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
3367   Value *ExtVal = SExt;
3368   bool HasMergedNonFreeExt = false;
3369   if (isa<ZExtInst>(SExtOpnd)) {
3370     // Replace s|zext(zext(opnd))
3371     // => zext(opnd).
3372     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
3373     Value *ZExt =
3374         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3375     TPT.replaceAllUsesWith(SExt, ZExt);
3376     TPT.eraseInstruction(SExt);
3377     ExtVal = ZExt;
3378   } else {
3379     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3380     // => z|sext(opnd).
3381     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3382   }
3383   CreatedInstsCost = 0;
3384
3385   // Remove dead code.
3386   if (SExtOpnd->use_empty())
3387     TPT.eraseInstruction(SExtOpnd);
3388
3389   // Check if the extension is still needed.
3390   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
3391   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3392     if (ExtInst) {
3393       if (Exts)
3394         Exts->push_back(ExtInst);
3395       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3396     }
3397     return ExtVal;
3398   }
3399
3400   // At this point we have: ext ty opnd to ty.
3401   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3402   Value *NextVal = ExtInst->getOperand(0);
3403   TPT.eraseInstruction(ExtInst, NextVal);
3404   return NextVal;
3405 }
3406
3407 Value *TypePromotionHelper::promoteOperandForOther(
3408     Instruction *Ext, TypePromotionTransaction &TPT,
3409     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3410     SmallVectorImpl<Instruction *> *Exts,
3411     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3412     bool IsSExt) {
3413   // By construction, the operand of Ext is an instruction. Otherwise we cannot
3414   // get through it and this method should not be called.
3415   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3416   CreatedInstsCost = 0;
3417   if (!ExtOpnd->hasOneUse()) {
3418     // ExtOpnd will be promoted.
3419     // All its uses, but Ext, will need to use a truncated value of the
3420     // promoted version.
3421     // Create the truncate now.
3422     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
3423     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3424       ITrunc->removeFromParent();
3425       // Insert it just after the definition.
3426       ITrunc->insertAfter(ExtOpnd);
3427       if (Truncs)
3428         Truncs->push_back(ITrunc);
3429     }
3430
3431     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
3432     // Restore the operand of Ext (which has been replaced by the previous call
3433     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
3434     TPT.setOperand(Ext, 0, ExtOpnd);
3435   }
3436
3437   // Get through the Instruction:
3438   // 1. Update its type.
3439   // 2. Replace the uses of Ext by Inst.
3440   // 3. Extend each operand that needs to be extended.
3441
3442   // Remember the original type of the instruction before promotion.
3443   // This is useful to know that the high bits are sign extended bits.
3444   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3445       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
3446   // Step #1.
3447   TPT.mutateType(ExtOpnd, Ext->getType());
3448   // Step #2.
3449   TPT.replaceAllUsesWith(Ext, ExtOpnd);
3450   // Step #3.
3451   Instruction *ExtForOpnd = Ext;
3452
3453   DEBUG(dbgs() << "Propagate Ext to operands\n");
3454   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
3455        ++OpIdx) {
3456     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3457     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3458         !shouldExtOperand(ExtOpnd, OpIdx)) {
3459       DEBUG(dbgs() << "No need to propagate\n");
3460       continue;
3461     }
3462     // Check if we can statically extend the operand.
3463     Value *Opnd = ExtOpnd->getOperand(OpIdx);
3464     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
3465       DEBUG(dbgs() << "Statically extend\n");
3466       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3467       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3468                             : Cst->getValue().zext(BitWidth);
3469       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
3470       continue;
3471     }
3472     // UndefValue are typed, so we have to statically sign extend them.
3473     if (isa<UndefValue>(Opnd)) {
3474       DEBUG(dbgs() << "Statically extend\n");
3475       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
3476       continue;
3477     }
3478
3479     // Otherwise we have to explicity sign extend the operand.
3480     // Check if Ext was reused to extend an operand.
3481     if (!ExtForOpnd) {
3482       // If yes, create a new one.
3483       DEBUG(dbgs() << "More operands to ext\n");
3484       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3485         : TPT.createZExt(Ext, Opnd, Ext->getType());
3486       if (!isa<Instruction>(ValForExtOpnd)) {
3487         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3488         continue;
3489       }
3490       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
3491     }
3492     if (Exts)
3493       Exts->push_back(ExtForOpnd);
3494     TPT.setOperand(ExtForOpnd, 0, Opnd);
3495
3496     // Move the sign extension before the insertion point.
3497     TPT.moveBefore(ExtForOpnd, ExtOpnd);
3498     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3499     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
3500     // If more sext are required, new instructions will have to be created.
3501     ExtForOpnd = nullptr;
3502   }
3503   if (ExtForOpnd == Ext) {
3504     DEBUG(dbgs() << "Extension is useless now\n");
3505     TPT.eraseInstruction(Ext);
3506   }
3507   return ExtOpnd;
3508 }
3509
3510 /// Check whether or not promoting an instruction to a wider type is profitable.
3511 /// \p NewCost gives the cost of extension instructions created by the
3512 /// promotion.
3513 /// \p OldCost gives the cost of extension instructions before the promotion
3514 /// plus the number of instructions that have been
3515 /// matched in the addressing mode the promotion.
3516 /// \p PromotedOperand is the value that has been promoted.
3517 /// \return True if the promotion is profitable, false otherwise.
3518 bool AddressingModeMatcher::isPromotionProfitable(
3519     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3520   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3521   // The cost of the new extensions is greater than the cost of the
3522   // old extension plus what we folded.
3523   // This is not profitable.
3524   if (NewCost > OldCost)
3525     return false;
3526   if (NewCost < OldCost)
3527     return true;
3528   // The promotion is neutral but it may help folding the sign extension in
3529   // loads for instance.
3530   // Check that we did not create an illegal instruction.
3531   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
3532 }
3533
3534 /// Given an instruction or constant expr, see if we can fold the operation
3535 /// into the addressing mode. If so, update the addressing mode and return
3536 /// true, otherwise return false without modifying AddrMode.
3537 /// If \p MovedAway is not NULL, it contains the information of whether or
3538 /// not AddrInst has to be folded into the addressing mode on success.
3539 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3540 /// because it has been moved away.
3541 /// Thus AddrInst must not be added in the matched instructions.
3542 /// This state can happen when AddrInst is a sext, since it may be moved away.
3543 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
3544 /// not be referenced anymore.
3545 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
3546                                                unsigned Depth,
3547                                                bool *MovedAway) {
3548   // Avoid exponential behavior on extremely deep expression trees.
3549   if (Depth >= 5) return false;
3550
3551   // By default, all matched instructions stay in place.
3552   if (MovedAway)
3553     *MovedAway = false;
3554
3555   switch (Opcode) {
3556   case Instruction::PtrToInt:
3557     // PtrToInt is always a noop, as we know that the int type is pointer sized.
3558     return matchAddr(AddrInst->getOperand(0), Depth);
3559   case Instruction::IntToPtr: {
3560     auto AS = AddrInst->getType()->getPointerAddressSpace();
3561     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
3562     // This inttoptr is a no-op if the integer type is pointer sized.
3563     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
3564       return matchAddr(AddrInst->getOperand(0), Depth);
3565     return false;
3566   }
3567   case Instruction::BitCast:
3568     // BitCast is always a noop, and we can handle it as long as it is
3569     // int->int or pointer->pointer (we don't want int<->fp or something).
3570     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3571          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3572         // Don't touch identity bitcasts.  These were probably put here by LSR,
3573         // and we don't want to mess around with them.  Assume it knows what it
3574         // is doing.
3575         AddrInst->getOperand(0)->getType() != AddrInst->getType())
3576       return matchAddr(AddrInst->getOperand(0), Depth);
3577     return false;
3578   case Instruction::AddrSpaceCast: {
3579     unsigned SrcAS
3580       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3581     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3582     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3583       return matchAddr(AddrInst->getOperand(0), Depth);
3584     return false;
3585   }
3586   case Instruction::Add: {
3587     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
3588     ExtAddrMode BackupAddrMode = AddrMode;
3589     unsigned OldSize = AddrModeInsts.size();
3590     // Start a transaction at this point.
3591     // The LHS may match but not the RHS.
3592     // Therefore, we need a higher level restoration point to undo partially
3593     // matched operation.
3594     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3595         TPT.getRestorationPoint();
3596
3597     if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3598         matchAddr(AddrInst->getOperand(0), Depth+1))
3599       return true;
3600
3601     // Restore the old addr mode info.
3602     AddrMode = BackupAddrMode;
3603     AddrModeInsts.resize(OldSize);
3604     TPT.rollback(LastKnownGood);
3605
3606     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
3607     if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3608         matchAddr(AddrInst->getOperand(1), Depth+1))
3609       return true;
3610
3611     // Otherwise we definitely can't merge the ADD in.
3612     AddrMode = BackupAddrMode;
3613     AddrModeInsts.resize(OldSize);
3614     TPT.rollback(LastKnownGood);
3615     break;
3616   }
3617   //case Instruction::Or:
3618   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3619   //break;
3620   case Instruction::Mul:
3621   case Instruction::Shl: {
3622     // Can only handle X*C and X << C.
3623     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
3624     if (!RHS)
3625       return false;
3626     int64_t Scale = RHS->getSExtValue();
3627     if (Opcode == Instruction::Shl)
3628       Scale = 1LL << Scale;
3629
3630     return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
3631   }
3632   case Instruction::GetElementPtr: {
3633     // Scan the GEP.  We check it if it contains constant offsets and at most
3634     // one variable offset.
3635     int VariableOperand = -1;
3636     unsigned VariableScale = 0;
3637
3638     int64_t ConstantOffset = 0;
3639     gep_type_iterator GTI = gep_type_begin(AddrInst);
3640     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3641       if (StructType *STy = GTI.getStructTypeOrNull()) {
3642         const StructLayout *SL = DL.getStructLayout(STy);
3643         unsigned Idx =
3644           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3645         ConstantOffset += SL->getElementOffset(Idx);
3646       } else {
3647         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
3648         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3649           ConstantOffset += CI->getSExtValue()*TypeSize;
3650         } else if (TypeSize) {  // Scales of zero don't do anything.
3651           // We only allow one variable index at the moment.
3652           if (VariableOperand != -1)
3653             return false;
3654
3655           // Remember the variable index.
3656           VariableOperand = i;
3657           VariableScale = TypeSize;
3658         }
3659       }
3660     }
3661
3662     // A common case is for the GEP to only do a constant offset.  In this case,
3663     // just add it to the disp field and check validity.
3664     if (VariableOperand == -1) {
3665       AddrMode.BaseOffs += ConstantOffset;
3666       if (ConstantOffset == 0 ||
3667           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
3668         // Check to see if we can fold the base pointer in too.
3669         if (matchAddr(AddrInst->getOperand(0), Depth+1))
3670           return true;
3671       }
3672       AddrMode.BaseOffs -= ConstantOffset;
3673       return false;
3674     }
3675
3676     // Save the valid addressing mode in case we can't match.
3677     ExtAddrMode BackupAddrMode = AddrMode;
3678     unsigned OldSize = AddrModeInsts.size();
3679
3680     // See if the scale and offset amount is valid for this target.
3681     AddrMode.BaseOffs += ConstantOffset;
3682
3683     // Match the base operand of the GEP.
3684     if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
3685       // If it couldn't be matched, just stuff the value in a register.
3686       if (AddrMode.HasBaseReg) {
3687         AddrMode = BackupAddrMode;
3688         AddrModeInsts.resize(OldSize);
3689         return false;
3690       }
3691       AddrMode.HasBaseReg = true;
3692       AddrMode.BaseReg = AddrInst->getOperand(0);
3693     }
3694
3695     // Match the remaining variable portion of the GEP.
3696     if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
3697                           Depth)) {
3698       // If it couldn't be matched, try stuffing the base into a register
3699       // instead of matching it, and retrying the match of the scale.
3700       AddrMode = BackupAddrMode;
3701       AddrModeInsts.resize(OldSize);
3702       if (AddrMode.HasBaseReg)
3703         return false;
3704       AddrMode.HasBaseReg = true;
3705       AddrMode.BaseReg = AddrInst->getOperand(0);
3706       AddrMode.BaseOffs += ConstantOffset;
3707       if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
3708                             VariableScale, Depth)) {
3709         // If even that didn't work, bail.
3710         AddrMode = BackupAddrMode;
3711         AddrModeInsts.resize(OldSize);
3712         return false;
3713       }
3714     }
3715
3716     return true;
3717   }
3718   case Instruction::SExt:
3719   case Instruction::ZExt: {
3720     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3721     if (!Ext)
3722       return false;
3723
3724     // Try to move this ext out of the way of the addressing mode.
3725     // Ask for a method for doing so.
3726     TypePromotionHelper::Action TPH =
3727         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
3728     if (!TPH)
3729       return false;
3730
3731     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3732         TPT.getRestorationPoint();
3733     unsigned CreatedInstsCost = 0;
3734     unsigned ExtCost = !TLI.isExtFree(Ext);
3735     Value *PromotedOperand =
3736         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
3737     // SExt has been moved away.
3738     // Thus either it will be rematched later in the recursive calls or it is
3739     // gone. Anyway, we must not fold it into the addressing mode at this point.
3740     // E.g.,
3741     // op = add opnd, 1
3742     // idx = ext op
3743     // addr = gep base, idx
3744     // is now:
3745     // promotedOpnd = ext opnd            <- no match here
3746     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
3747     // addr = gep base, op                <- match
3748     if (MovedAway)
3749       *MovedAway = true;
3750
3751     assert(PromotedOperand &&
3752            "TypePromotionHelper should have filtered out those cases");
3753
3754     ExtAddrMode BackupAddrMode = AddrMode;
3755     unsigned OldSize = AddrModeInsts.size();
3756
3757     if (!matchAddr(PromotedOperand, Depth) ||
3758         // The total of the new cost is equal to the cost of the created
3759         // instructions.
3760         // The total of the old cost is equal to the cost of the extension plus
3761         // what we have saved in the addressing mode.
3762         !isPromotionProfitable(CreatedInstsCost,
3763                                ExtCost + (AddrModeInsts.size() - OldSize),
3764                                PromotedOperand)) {
3765       AddrMode = BackupAddrMode;
3766       AddrModeInsts.resize(OldSize);
3767       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3768       TPT.rollback(LastKnownGood);
3769       return false;
3770     }
3771     return true;
3772   }
3773   }
3774   return false;
3775 }
3776
3777 /// If we can, try to add the value of 'Addr' into the current addressing mode.
3778 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3779 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
3780 /// for the target.
3781 ///
3782 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
3783   // Start a transaction at this point that we will rollback if the matching
3784   // fails.
3785   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3786       TPT.getRestorationPoint();
3787   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3788     // Fold in immediates if legal for the target.
3789     AddrMode.BaseOffs += CI->getSExtValue();
3790     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3791       return true;
3792     AddrMode.BaseOffs -= CI->getSExtValue();
3793   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3794     // If this is a global variable, try to fold it into the addressing mode.
3795     if (!AddrMode.BaseGV) {
3796       AddrMode.BaseGV = GV;
3797       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3798         return true;
3799       AddrMode.BaseGV = nullptr;
3800     }
3801   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3802     ExtAddrMode BackupAddrMode = AddrMode;
3803     unsigned OldSize = AddrModeInsts.size();
3804
3805     // Check to see if it is possible to fold this operation.
3806     bool MovedAway = false;
3807     if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
3808       // This instruction may have been moved away. If so, there is nothing
3809       // to check here.
3810       if (MovedAway)
3811         return true;
3812       // Okay, it's possible to fold this.  Check to see if it is actually
3813       // *profitable* to do so.  We use a simple cost model to avoid increasing
3814       // register pressure too much.
3815       if (I->hasOneUse() ||
3816           isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
3817         AddrModeInsts.push_back(I);
3818         return true;
3819       }
3820
3821       // It isn't profitable to do this, roll back.
3822       //cerr << "NOT FOLDING: " << *I;
3823       AddrMode = BackupAddrMode;
3824       AddrModeInsts.resize(OldSize);
3825       TPT.rollback(LastKnownGood);
3826     }
3827   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
3828     if (matchOperationAddr(CE, CE->getOpcode(), Depth))
3829       return true;
3830     TPT.rollback(LastKnownGood);
3831   } else if (isa<ConstantPointerNull>(Addr)) {
3832     // Null pointer gets folded without affecting the addressing mode.
3833     return true;
3834   }
3835
3836   // Worse case, the target should support [reg] addressing modes. :)
3837   if (!AddrMode.HasBaseReg) {
3838     AddrMode.HasBaseReg = true;
3839     AddrMode.BaseReg = Addr;
3840     // Still check for legality in case the target supports [imm] but not [i+r].
3841     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3842       return true;
3843     AddrMode.HasBaseReg = false;
3844     AddrMode.BaseReg = nullptr;
3845   }
3846
3847   // If the base register is already taken, see if we can do [r+r].
3848   if (AddrMode.Scale == 0) {
3849     AddrMode.Scale = 1;
3850     AddrMode.ScaledReg = Addr;
3851     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
3852       return true;
3853     AddrMode.Scale = 0;
3854     AddrMode.ScaledReg = nullptr;
3855   }
3856   // Couldn't match.
3857   TPT.rollback(LastKnownGood);
3858   return false;
3859 }
3860
3861 /// Check to see if all uses of OpVal by the specified inline asm call are due
3862 /// to memory operands. If so, return true, otherwise return false.
3863 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
3864                                     const TargetLowering &TLI,
3865                                     const TargetRegisterInfo &TRI) {
3866   const Function *F = CI->getParent()->getParent();
3867   TargetLowering::AsmOperandInfoVector TargetConstraints =
3868       TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
3869                             ImmutableCallSite(CI));
3870
3871   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3872     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3873
3874     // Compute the constraint code and ConstraintType to use.
3875     TLI.ComputeConstraintToUse(OpInfo, SDValue());
3876
3877     // If this asm operand is our Value*, and if it isn't an indirect memory
3878     // operand, we can't fold it!
3879     if (OpInfo.CallOperandVal == OpVal &&
3880         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3881          !OpInfo.isIndirect))
3882       return false;
3883   }
3884
3885   return true;
3886 }
3887
3888 /// Recursively walk all the uses of I until we find a memory use.
3889 /// If we find an obviously non-foldable instruction, return true.
3890 /// Add the ultimately found memory instructions to MemoryUses.
3891 static bool FindAllMemoryUses(
3892     Instruction *I,
3893     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3894     SmallPtrSetImpl<Instruction *> &ConsideredInsts,
3895     const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
3896   // If we already considered this instruction, we're done.
3897   if (!ConsideredInsts.insert(I).second)
3898     return false;
3899
3900   // If this is an obviously unfoldable instruction, bail out.
3901   if (!MightBeFoldableInst(I))
3902     return true;
3903
3904   const bool OptSize = I->getFunction()->optForSize();
3905
3906   // Loop over all the uses, recursively processing them.
3907   for (Use &U : I->uses()) {
3908     Instruction *UserI = cast<Instruction>(U.getUser());
3909
3910     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3911       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
3912       continue;
3913     }
3914
3915     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3916       unsigned opNo = U.getOperandNo();
3917       if (opNo != StoreInst::getPointerOperandIndex())
3918         return true; // Storing addr, not into addr.
3919       MemoryUses.push_back(std::make_pair(SI, opNo));
3920       continue;
3921     }
3922
3923     if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
3924       unsigned opNo = U.getOperandNo();
3925       if (opNo != AtomicRMWInst::getPointerOperandIndex())
3926         return true; // Storing addr, not into addr.
3927       MemoryUses.push_back(std::make_pair(RMW, opNo));
3928       continue;
3929     }
3930
3931     if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
3932       unsigned opNo = U.getOperandNo();
3933       if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
3934         return true; // Storing addr, not into addr.
3935       MemoryUses.push_back(std::make_pair(CmpX, opNo));
3936       continue;
3937     }
3938
3939     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
3940       // If this is a cold call, we can sink the addressing calculation into
3941       // the cold path.  See optimizeCallInst
3942       if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3943         continue;
3944
3945       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3946       if (!IA) return true;
3947
3948       // If this is a memory operand, we're cool, otherwise bail out.
3949       if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
3950         return true;
3951       continue;
3952     }
3953
3954     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
3955       return true;
3956   }
3957
3958   return false;
3959 }
3960
3961 /// Return true if Val is already known to be live at the use site that we're
3962 /// folding it into. If so, there is no cost to include it in the addressing
3963 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3964 /// instruction already.
3965 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
3966                                                    Value *KnownLive2) {
3967   // If Val is either of the known-live values, we know it is live!
3968   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
3969     return true;
3970
3971   // All values other than instructions and arguments (e.g. constants) are live.
3972   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
3973
3974   // If Val is a constant sized alloca in the entry block, it is live, this is
3975   // true because it is just a reference to the stack/frame pointer, which is
3976   // live for the whole function.
3977   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3978     if (AI->isStaticAlloca())
3979       return true;
3980
3981   // Check to see if this value is already used in the memory instruction's
3982   // block.  If so, it's already live into the block at the very least, so we
3983   // can reasonably fold it.
3984   return Val->isUsedInBasicBlock(MemoryInst->getParent());
3985 }
3986
3987 /// It is possible for the addressing mode of the machine to fold the specified
3988 /// instruction into a load or store that ultimately uses it.
3989 /// However, the specified instruction has multiple uses.
3990 /// Given this, it may actually increase register pressure to fold it
3991 /// into the load. For example, consider this code:
3992 ///
3993 ///     X = ...
3994 ///     Y = X+1
3995 ///     use(Y)   -> nonload/store
3996 ///     Z = Y+1
3997 ///     load Z
3998 ///
3999 /// In this case, Y has multiple uses, and can be folded into the load of Z
4000 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
4001 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
4002 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
4003 /// number of computations either.
4004 ///
4005 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
4006 /// X was live across 'load Z' for other reasons, we actually *would* want to
4007 /// fold the addressing mode in the Z case.  This would make Y die earlier.
4008 bool AddressingModeMatcher::
4009 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4010                                      ExtAddrMode &AMAfter) {
4011   if (IgnoreProfitability) return true;
4012
4013   // AMBefore is the addressing mode before this instruction was folded into it,
4014   // and AMAfter is the addressing mode after the instruction was folded.  Get
4015   // the set of registers referenced by AMAfter and subtract out those
4016   // referenced by AMBefore: this is the set of values which folding in this
4017   // address extends the lifetime of.
4018   //
4019   // Note that there are only two potential values being referenced here,
4020   // BaseReg and ScaleReg (global addresses are always available, as are any
4021   // folded immediates).
4022   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4023
4024   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4025   // lifetime wasn't extended by adding this instruction.
4026   if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4027     BaseReg = nullptr;
4028   if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4029     ScaledReg = nullptr;
4030
4031   // If folding this instruction (and it's subexprs) didn't extend any live
4032   // ranges, we're ok with it.
4033   if (!BaseReg && !ScaledReg)
4034     return true;
4035
4036   // If all uses of this instruction can have the address mode sunk into them,
4037   // we can remove the addressing mode and effectively trade one live register
4038   // for another (at worst.)  In this context, folding an addressing mode into
4039   // the use is just a particularly nice way of sinking it.
4040   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4041   SmallPtrSet<Instruction*, 16> ConsideredInsts;
4042   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
4043     return false;  // Has a non-memory, non-foldable use!
4044
4045   // Now that we know that all uses of this instruction are part of a chain of
4046   // computation involving only operations that could theoretically be folded
4047   // into a memory use, loop over each of these memory operation uses and see
4048   // if they could  *actually* fold the instruction.  The assumption is that
4049   // addressing modes are cheap and that duplicating the computation involved
4050   // many times is worthwhile, even on a fastpath. For sinking candidates
4051   // (i.e. cold call sites), this serves as a way to prevent excessive code
4052   // growth since most architectures have some reasonable small and fast way to
4053   // compute an effective address.  (i.e LEA on x86)
4054   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4055   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4056     Instruction *User = MemoryUses[i].first;
4057     unsigned OpNo = MemoryUses[i].second;
4058
4059     // Get the access type of this use.  If the use isn't a pointer, we don't
4060     // know what it accesses.
4061     Value *Address = User->getOperand(OpNo);
4062     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4063     if (!AddrTy)
4064       return false;
4065     Type *AddressAccessTy = AddrTy->getElementType();
4066     unsigned AS = AddrTy->getAddressSpace();
4067
4068     // Do a match against the root of this address, ignoring profitability. This
4069     // will tell us if the addressing mode for the memory operation will
4070     // *actually* cover the shared instruction.
4071     ExtAddrMode Result;
4072     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4073         TPT.getRestorationPoint();
4074     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4075                                   AddressAccessTy, AS,
4076                                   MemoryInst, Result, InsertedInsts,
4077                                   PromotedInsts, TPT);
4078     Matcher.IgnoreProfitability = true;
4079     bool Success = Matcher.matchAddr(Address, 0);
4080     (void)Success; assert(Success && "Couldn't select *anything*?");
4081
4082     // The match was to check the profitability, the changes made are not
4083     // part of the original matcher. Therefore, they should be dropped
4084     // otherwise the original matcher will not present the right state.
4085     TPT.rollback(LastKnownGood);
4086
4087     // If the match didn't cover I, then it won't be shared by it.
4088     if (!is_contained(MatchedAddrModeInsts, I))
4089       return false;
4090
4091     MatchedAddrModeInsts.clear();
4092   }
4093
4094   return true;
4095 }
4096
4097 } // end anonymous namespace
4098
4099 /// Return true if the specified values are defined in a
4100 /// different basic block than BB.
4101 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4102   if (Instruction *I = dyn_cast<Instruction>(V))
4103     return I->getParent() != BB;
4104   return false;
4105 }
4106
4107 /// Sink addressing mode computation immediate before MemoryInst if doing so
4108 /// can be done without increasing register pressure.  The need for the
4109 /// register pressure constraint means this can end up being an all or nothing
4110 /// decision for all uses of the same addressing computation.
4111 ///
4112 /// Load and Store Instructions often have addressing modes that can do
4113 /// significant amounts of computation. As such, instruction selection will try
4114 /// to get the load or store to do as much computation as possible for the
4115 /// program. The problem is that isel can only see within a single block. As
4116 /// such, we sink as much legal addressing mode work into the block as possible.
4117 ///
4118 /// This method is used to optimize both load/store and inline asms with memory
4119 /// operands.  It's also used to sink addressing computations feeding into cold
4120 /// call sites into their (cold) basic block.
4121 ///
4122 /// The motivation for handling sinking into cold blocks is that doing so can
4123 /// both enable other address mode sinking (by satisfying the register pressure
4124 /// constraint above), and reduce register pressure globally (by removing the
4125 /// addressing mode computation from the fast path entirely.).
4126 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
4127                                         Type *AccessTy, unsigned AddrSpace) {
4128   Value *Repl = Addr;
4129
4130   // Try to collapse single-value PHI nodes.  This is necessary to undo
4131   // unprofitable PRE transformations.
4132   SmallVector<Value*, 8> worklist;
4133   SmallPtrSet<Value*, 16> Visited;
4134   worklist.push_back(Addr);
4135
4136   // Use a worklist to iteratively look through PHI nodes, and ensure that
4137   // the addressing mode obtained from the non-PHI roots of the graph
4138   // are equivalent.
4139   Value *Consensus = nullptr;
4140   unsigned NumUsesConsensus = 0;
4141   bool IsNumUsesConsensusValid = false;
4142   SmallVector<Instruction*, 16> AddrModeInsts;
4143   ExtAddrMode AddrMode;
4144   TypePromotionTransaction TPT(RemovedInsts);
4145   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4146       TPT.getRestorationPoint();
4147   while (!worklist.empty()) {
4148     Value *V = worklist.back();
4149     worklist.pop_back();
4150
4151     // Break use-def graph loops.
4152     if (!Visited.insert(V).second) {
4153       Consensus = nullptr;
4154       break;
4155     }
4156
4157     // For a PHI node, push all of its incoming values.
4158     if (PHINode *P = dyn_cast<PHINode>(V)) {
4159       for (Value *IncValue : P->incoming_values())
4160         worklist.push_back(IncValue);
4161       continue;
4162     }
4163
4164     // For non-PHIs, determine the addressing mode being computed.  Note that
4165     // the result may differ depending on what other uses our candidate
4166     // addressing instructions might have.
4167     SmallVector<Instruction*, 16> NewAddrModeInsts;
4168     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4169       V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
4170       InsertedInsts, PromotedInsts, TPT);
4171
4172     // This check is broken into two cases with very similar code to avoid using
4173     // getNumUses() as much as possible. Some values have a lot of uses, so
4174     // calling getNumUses() unconditionally caused a significant compile-time
4175     // regression.
4176     if (!Consensus) {
4177       Consensus = V;
4178       AddrMode = NewAddrMode;
4179       AddrModeInsts = NewAddrModeInsts;
4180       continue;
4181     } else if (NewAddrMode == AddrMode) {
4182       if (!IsNumUsesConsensusValid) {
4183         NumUsesConsensus = Consensus->getNumUses();
4184         IsNumUsesConsensusValid = true;
4185       }
4186
4187       // Ensure that the obtained addressing mode is equivalent to that obtained
4188       // for all other roots of the PHI traversal.  Also, when choosing one
4189       // such root as representative, select the one with the most uses in order
4190       // to keep the cost modeling heuristics in AddressingModeMatcher
4191       // applicable.
4192       unsigned NumUses = V->getNumUses();
4193       if (NumUses > NumUsesConsensus) {
4194         Consensus = V;
4195         NumUsesConsensus = NumUses;
4196         AddrModeInsts = NewAddrModeInsts;
4197       }
4198       continue;
4199     }
4200
4201     Consensus = nullptr;
4202     break;
4203   }
4204
4205   // If the addressing mode couldn't be determined, or if multiple different
4206   // ones were determined, bail out now.
4207   if (!Consensus) {
4208     TPT.rollback(LastKnownGood);
4209     return false;
4210   }
4211   TPT.commit();
4212
4213   // If all the instructions matched are already in this BB, don't do anything.
4214   if (none_of(AddrModeInsts, [&](Value *V) {
4215         return IsNonLocalValue(V, MemoryInst->getParent());
4216       })) {
4217     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
4218     return false;
4219   }
4220
4221   // Insert this computation right after this user.  Since our caller is
4222   // scanning from the top of the BB to the bottom, reuse of the expr are
4223   // guaranteed to happen later.
4224   IRBuilder<> Builder(MemoryInst);
4225
4226   // Now that we determined the addressing expression we want to use and know
4227   // that we have to sink it into this block.  Check to see if we have already
4228   // done this for some other load/store instr in this block.  If so, reuse the
4229   // computation.
4230   Value *&SunkAddr = SunkAddrs[Addr];
4231   if (SunkAddr) {
4232     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
4233                  << *MemoryInst << "\n");
4234     if (SunkAddr->getType() != Addr->getType())
4235       SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4236   } else if (AddrSinkUsingGEPs ||
4237              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
4238               SubtargetInfo->useAA())) {
4239     // By default, we use the GEP-based method when AA is used later. This
4240     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4241     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4242                  << *MemoryInst << "\n");
4243     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4244     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
4245
4246     // First, find the pointer.
4247     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4248       ResultPtr = AddrMode.BaseReg;
4249       AddrMode.BaseReg = nullptr;
4250     }
4251
4252     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4253       // We can't add more than one pointer together, nor can we scale a
4254       // pointer (both of which seem meaningless).
4255       if (ResultPtr || AddrMode.Scale != 1)
4256         return false;
4257
4258       ResultPtr = AddrMode.ScaledReg;
4259       AddrMode.Scale = 0;
4260     }
4261
4262     if (AddrMode.BaseGV) {
4263       if (ResultPtr)
4264         return false;
4265
4266       ResultPtr = AddrMode.BaseGV;
4267     }
4268
4269     // If the real base value actually came from an inttoptr, then the matcher
4270     // will look through it and provide only the integer value. In that case,
4271     // use it here.
4272     if (!ResultPtr && AddrMode.BaseReg) {
4273       ResultPtr =
4274         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
4275       AddrMode.BaseReg = nullptr;
4276     } else if (!ResultPtr && AddrMode.Scale == 1) {
4277       ResultPtr =
4278         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4279       AddrMode.Scale = 0;
4280     }
4281
4282     if (!ResultPtr &&
4283         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4284       SunkAddr = Constant::getNullValue(Addr->getType());
4285     } else if (!ResultPtr) {
4286       return false;
4287     } else {
4288       Type *I8PtrTy =
4289           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4290       Type *I8Ty = Builder.getInt8Ty();
4291
4292       // Start with the base register. Do this first so that subsequent address
4293       // matching finds it last, which will prevent it from trying to match it
4294       // as the scaled value in case it happens to be a mul. That would be
4295       // problematic if we've sunk a different mul for the scale, because then
4296       // we'd end up sinking both muls.
4297       if (AddrMode.BaseReg) {
4298         Value *V = AddrMode.BaseReg;
4299         if (V->getType() != IntPtrTy)
4300           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4301
4302         ResultIndex = V;
4303       }
4304
4305       // Add the scale value.
4306       if (AddrMode.Scale) {
4307         Value *V = AddrMode.ScaledReg;
4308         if (V->getType() == IntPtrTy) {
4309           // done.
4310         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4311                    cast<IntegerType>(V->getType())->getBitWidth()) {
4312           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4313         } else {
4314           // It is only safe to sign extend the BaseReg if we know that the math
4315           // required to create it did not overflow before we extend it. Since
4316           // the original IR value was tossed in favor of a constant back when
4317           // the AddrMode was created we need to bail out gracefully if widths
4318           // do not match instead of extending it.
4319           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4320           if (I && (ResultIndex != AddrMode.BaseReg))
4321             I->eraseFromParent();
4322           return false;
4323         }
4324
4325         if (AddrMode.Scale != 1)
4326           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4327                                 "sunkaddr");
4328         if (ResultIndex)
4329           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4330         else
4331           ResultIndex = V;
4332       }
4333
4334       // Add in the Base Offset if present.
4335       if (AddrMode.BaseOffs) {
4336         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4337         if (ResultIndex) {
4338           // We need to add this separately from the scale above to help with
4339           // SDAG consecutive load/store merging.
4340           if (ResultPtr->getType() != I8PtrTy)
4341             ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4342           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4343         }
4344
4345         ResultIndex = V;
4346       }
4347
4348       if (!ResultIndex) {
4349         SunkAddr = ResultPtr;
4350       } else {
4351         if (ResultPtr->getType() != I8PtrTy)
4352           ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4353         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4354       }
4355
4356       if (SunkAddr->getType() != Addr->getType())
4357         SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4358     }
4359   } else {
4360     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4361                  << *MemoryInst << "\n");
4362     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4363     Value *Result = nullptr;
4364
4365     // Start with the base register. Do this first so that subsequent address
4366     // matching finds it last, which will prevent it from trying to match it
4367     // as the scaled value in case it happens to be a mul. That would be
4368     // problematic if we've sunk a different mul for the scale, because then
4369     // we'd end up sinking both muls.
4370     if (AddrMode.BaseReg) {
4371       Value *V = AddrMode.BaseReg;
4372       if (V->getType()->isPointerTy())
4373         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4374       if (V->getType() != IntPtrTy)
4375         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4376       Result = V;
4377     }
4378
4379     // Add the scale value.
4380     if (AddrMode.Scale) {
4381       Value *V = AddrMode.ScaledReg;
4382       if (V->getType() == IntPtrTy) {
4383         // done.
4384       } else if (V->getType()->isPointerTy()) {
4385         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4386       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4387                  cast<IntegerType>(V->getType())->getBitWidth()) {
4388         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4389       } else {
4390         // It is only safe to sign extend the BaseReg if we know that the math
4391         // required to create it did not overflow before we extend it. Since
4392         // the original IR value was tossed in favor of a constant back when
4393         // the AddrMode was created we need to bail out gracefully if widths
4394         // do not match instead of extending it.
4395         Instruction *I = dyn_cast_or_null<Instruction>(Result);
4396         if (I && (Result != AddrMode.BaseReg))
4397           I->eraseFromParent();
4398         return false;
4399       }
4400       if (AddrMode.Scale != 1)
4401         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4402                               "sunkaddr");
4403       if (Result)
4404         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4405       else
4406         Result = V;
4407     }
4408
4409     // Add in the BaseGV if present.
4410     if (AddrMode.BaseGV) {
4411       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
4412       if (Result)
4413         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4414       else
4415         Result = V;
4416     }
4417
4418     // Add in the Base Offset if present.
4419     if (AddrMode.BaseOffs) {
4420       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4421       if (Result)
4422         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4423       else
4424         Result = V;
4425     }
4426
4427     if (!Result)
4428       SunkAddr = Constant::getNullValue(Addr->getType());
4429     else
4430       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
4431   }
4432
4433   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
4434
4435   // If we have no uses, recursively delete the value and all dead instructions
4436   // using it.
4437   if (Repl->use_empty()) {
4438     // This can cause recursive deletion, which can invalidate our iterator.
4439     // Use a WeakVH to hold onto it in case this happens.
4440     Value *CurValue = &*CurInstIterator;
4441     WeakVH IterHandle(CurValue);
4442     BasicBlock *BB = CurInstIterator->getParent();
4443
4444     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
4445
4446     if (IterHandle != CurValue) {
4447       // If the iterator instruction was recursively deleted, start over at the
4448       // start of the block.
4449       CurInstIterator = BB->begin();
4450       SunkAddrs.clear();
4451     }
4452   }
4453   ++NumMemoryInsts;
4454   return true;
4455 }
4456
4457 /// If there are any memory operands, use OptimizeMemoryInst to sink their
4458 /// address computing into the block when possible / profitable.
4459 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
4460   bool MadeChange = false;
4461
4462   const TargetRegisterInfo *TRI =
4463       TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
4464   TargetLowering::AsmOperandInfoVector TargetConstraints =
4465       TLI->ParseConstraints(*DL, TRI, CS);
4466   unsigned ArgNo = 0;
4467   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4468     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4469
4470     // Compute the constraint code and ConstraintType to use.
4471     TLI->ComputeConstraintToUse(OpInfo, SDValue());
4472
4473     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4474         OpInfo.isIndirect) {
4475       Value *OpVal = CS->getArgOperand(ArgNo++);
4476       MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
4477     } else if (OpInfo.Type == InlineAsm::isInput)
4478       ArgNo++;
4479   }
4480
4481   return MadeChange;
4482 }
4483
4484 /// \brief Check if all the uses of \p Val are equivalent (or free) zero or
4485 /// sign extensions.
4486 static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4487   assert(!Val->use_empty() && "Input must have at least one use");
4488   const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
4489   bool IsSExt = isa<SExtInst>(FirstUser);
4490   Type *ExtTy = FirstUser->getType();
4491   for (const User *U : Val->users()) {
4492     const Instruction *UI = cast<Instruction>(U);
4493     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4494       return false;
4495     Type *CurTy = UI->getType();
4496     // Same input and output types: Same instruction after CSE.
4497     if (CurTy == ExtTy)
4498       continue;
4499
4500     // If IsSExt is true, we are in this situation:
4501     // a = Val
4502     // b = sext ty1 a to ty2
4503     // c = sext ty1 a to ty3
4504     // Assuming ty2 is shorter than ty3, this could be turned into:
4505     // a = Val
4506     // b = sext ty1 a to ty2
4507     // c = sext ty2 b to ty3
4508     // However, the last sext is not free.
4509     if (IsSExt)
4510       return false;
4511
4512     // This is a ZExt, maybe this is free to extend from one type to another.
4513     // In that case, we would not account for a different use.
4514     Type *NarrowTy;
4515     Type *LargeTy;
4516     if (ExtTy->getScalarType()->getIntegerBitWidth() >
4517         CurTy->getScalarType()->getIntegerBitWidth()) {
4518       NarrowTy = CurTy;
4519       LargeTy = ExtTy;
4520     } else {
4521       NarrowTy = ExtTy;
4522       LargeTy = CurTy;
4523     }
4524
4525     if (!TLI.isZExtFree(NarrowTy, LargeTy))
4526       return false;
4527   }
4528   // All uses are the same or can be derived from one another for free.
4529   return true;
4530 }
4531
4532 /// \brief Try to speculatively promote extensions in \p Exts and continue
4533 /// promoting through newly promoted operands recursively as far as doing so is
4534 /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4535 /// When some promotion happened, \p TPT contains the proper state to revert
4536 /// them.
4537 ///
4538 /// \return true if some promotion happened, false otherwise.
4539 bool CodeGenPrepare::tryToPromoteExts(
4540     TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4541     SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4542     unsigned CreatedInstsCost) {
4543   bool Promoted = false;
4544
4545   // Iterate over all the extensions to try to promote them.
4546   for (auto I : Exts) {
4547     // Early check if we directly have ext(load).
4548     if (isa<LoadInst>(I->getOperand(0))) {
4549       ProfitablyMovedExts.push_back(I);
4550       continue;
4551     }
4552
4553     // Check whether or not we want to do any promotion.  The reason we have
4554     // this check inside the for loop is to catch the case where an extension
4555     // is directly fed by a load because in such case the extension can be moved
4556     // up without any promotion on its operands.
4557     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4558       return false;
4559
4560     // Get the action to perform the promotion.
4561     TypePromotionHelper::Action TPH =
4562         TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
4563     // Check if we can promote.
4564     if (!TPH) {
4565       // Save the current extension as we cannot move up through its operand.
4566       ProfitablyMovedExts.push_back(I);
4567       continue;
4568     }
4569
4570     // Save the current state.
4571     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4572         TPT.getRestorationPoint();
4573     SmallVector<Instruction *, 4> NewExts;
4574     unsigned NewCreatedInstsCost = 0;
4575     unsigned ExtCost = !TLI->isExtFree(I);
4576     // Promote.
4577     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4578                              &NewExts, nullptr, *TLI);
4579     assert(PromotedVal &&
4580            "TypePromotionHelper should have filtered out those cases");
4581
4582     // We would be able to merge only one extension in a load.
4583     // Therefore, if we have more than 1 new extension we heuristically
4584     // cut this search path, because it means we degrade the code quality.
4585     // With exactly 2, the transformation is neutral, because we will merge
4586     // one extension but leave one. However, we optimistically keep going,
4587     // because the new extension may be removed too.
4588     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4589     // FIXME: It would be possible to propagate a negative value instead of
4590     // conservatively ceiling it to 0.
4591     TotalCreatedInstsCost =
4592         std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
4593     if (!StressExtLdPromotion &&
4594         (TotalCreatedInstsCost > 1 ||
4595          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
4596       // This promotion is not profitable, rollback to the previous state, and
4597       // save the current extension in ProfitablyMovedExts as the latest
4598       // speculative promotion turned out to be unprofitable.
4599       TPT.rollback(LastKnownGood);
4600       ProfitablyMovedExts.push_back(I);
4601       continue;
4602     }
4603     // Continue promoting NewExts as far as doing so is profitable.
4604     SmallVector<Instruction *, 2> NewlyMovedExts;
4605     (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4606     bool NewPromoted = false;
4607     for (auto ExtInst : NewlyMovedExts) {
4608       Instruction *MovedExt = cast<Instruction>(ExtInst);
4609       Value *ExtOperand = MovedExt->getOperand(0);
4610       // If we have reached to a load, we need this extra profitability check
4611       // as it could potentially be merged into an ext(load).
4612       if (isa<LoadInst>(ExtOperand) &&
4613           !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4614             (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4615         continue;
4616
4617       ProfitablyMovedExts.push_back(MovedExt);
4618       NewPromoted = true;
4619     }
4620
4621     // If none of speculative promotions for NewExts is profitable, rollback
4622     // and save the current extension (I) as the last profitable extension.
4623     if (!NewPromoted) {
4624       TPT.rollback(LastKnownGood);
4625       ProfitablyMovedExts.push_back(I);
4626       continue;
4627     }
4628     // The promotion is profitable.
4629     Promoted = true;
4630   }
4631   return Promoted;
4632 }
4633
4634 /// Merging redundant sexts when one is dominating the other.
4635 bool CodeGenPrepare::mergeSExts(Function &F) {
4636   DominatorTree DT(F);
4637   bool Changed = false;
4638   for (auto &Entry : ValToSExtendedUses) {
4639     SExts &Insts = Entry.second;
4640     SExts CurPts;
4641     for (Instruction *Inst : Insts) {
4642       if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4643           Inst->getOperand(0) != Entry.first)
4644         continue;
4645       bool inserted = false;
4646       for (auto &Pt : CurPts) {
4647         if (DT.dominates(Inst, Pt)) {
4648           Pt->replaceAllUsesWith(Inst);
4649           RemovedInsts.insert(Pt);
4650           Pt->removeFromParent();
4651           Pt = Inst;
4652           inserted = true;
4653           Changed = true;
4654           break;
4655         }
4656         if (!DT.dominates(Pt, Inst))
4657           // Give up if we need to merge in a common dominator as the
4658           // expermients show it is not profitable.
4659           continue;
4660         Inst->replaceAllUsesWith(Pt);
4661         RemovedInsts.insert(Inst);
4662         Inst->removeFromParent();
4663         inserted = true;
4664         Changed = true;
4665         break;
4666       }
4667       if (!inserted)
4668         CurPts.push_back(Inst);
4669     }
4670   }
4671   return Changed;
4672 }
4673
4674 /// Return true, if an ext(load) can be formed from an extension in
4675 /// \p MovedExts.
4676 bool CodeGenPrepare::canFormExtLd(
4677     const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4678     Instruction *&Inst, bool HasPromoted) {
4679   for (auto *MovedExtInst : MovedExts) {
4680     if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4681       LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4682       Inst = MovedExtInst;
4683       break;
4684     }
4685   }
4686   if (!LI)
4687     return false;
4688
4689   // If they're already in the same block, there's nothing to do.
4690   // Make the cheap checks first if we did not promote.
4691   // If we promoted, we need to check if it is indeed profitable.
4692   if (!HasPromoted && LI->getParent() == Inst->getParent())
4693     return false;
4694
4695   EVT VT = TLI->getValueType(*DL, Inst->getType());
4696   EVT LoadVT = TLI->getValueType(*DL, LI->getType());
4697
4698   // If the load has other users and the truncate is not free, this probably
4699   // isn't worthwhile.
4700   if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
4701       !TLI->isTruncateFree(Inst->getType(), LI->getType()))
4702     return false;
4703
4704   // Check whether the target supports casts folded into loads.
4705   unsigned LType;
4706   if (isa<ZExtInst>(Inst))
4707     LType = ISD::ZEXTLOAD;
4708   else {
4709     assert(isa<SExtInst>(Inst) && "Unexpected ext type!");
4710     LType = ISD::SEXTLOAD;
4711   }
4712
4713   return TLI->isLoadExtLegal(LType, VT, LoadVT);
4714 }
4715
4716 /// Move a zext or sext fed by a load into the same basic block as the load,
4717 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
4718 /// extend into the load.
4719 ///
4720 /// E.g.,
4721 /// \code
4722 /// %ld = load i32* %addr
4723 /// %add = add nuw i32 %ld, 4
4724 /// %zext = zext i32 %add to i64
4725 // \endcode
4726 /// =>
4727 /// \code
4728 /// %ld = load i32* %addr
4729 /// %zext = zext i32 %ld to i64
4730 /// %add = add nuw i64 %zext, 4
4731 /// \encode
4732 /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4733 /// allow us to match zext(load i32*) to i64.
4734 ///
4735 /// Also, try to promote the computations used to obtain a sign extended
4736 /// value used into memory accesses.
4737 /// E.g.,
4738 /// \code
4739 /// a = add nsw i32 b, 3
4740 /// d = sext i32 a to i64
4741 /// e = getelementptr ..., i64 d
4742 /// \endcode
4743 /// =>
4744 /// \code
4745 /// f = sext i32 b to i64
4746 /// a = add nsw i64 f, 3
4747 /// e = getelementptr ..., i64 a
4748 /// \endcode
4749 ///
4750 /// \p Inst[in/out] the extension may be modified during the process if some
4751 /// promotions apply.
4752 bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4753   // ExtLoad formation and address type promotion infrastructure requires TLI to
4754   // be effective.
4755   if (!TLI)
4756     return false;
4757
4758   bool AllowPromotionWithoutCommonHeader = false;
4759   /// See if it is an interesting sext operations for the address type
4760   /// promotion before trying to promote it, e.g., the ones with the right
4761   /// type and used in memory accesses.
4762   bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4763       *Inst, AllowPromotionWithoutCommonHeader);
4764   TypePromotionTransaction TPT(RemovedInsts);
4765   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4766       TPT.getRestorationPoint();
4767   SmallVector<Instruction *, 1> Exts;
4768   SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4769   Exts.push_back(Inst);
4770
4771   bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
4772
4773   // Look for a load being extended.
4774   LoadInst *LI = nullptr;
4775   Instruction *ExtFedByLoad;
4776
4777   // Try to promote a chain of computation if it allows to form an extended
4778   // load.
4779   if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4780     assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4781     TPT.commit();
4782     // Move the extend into the same block as the load
4783     ExtFedByLoad->removeFromParent();
4784     ExtFedByLoad->insertAfter(LI);
4785     // CGP does not check if the zext would be speculatively executed when moved
4786     // to the same basic block as the load. Preserving its original location
4787     // would pessimize the debugging experience, as well as negatively impact
4788     // the quality of sample pgo. We don't want to use "line 0" as that has a
4789     // size cost in the line-table section and logically the zext can be seen as
4790     // part of the load. Therefore we conservatively reuse the same debug
4791     // location for the load and the zext.
4792     ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
4793     ++NumExtsMoved;
4794     Inst = ExtFedByLoad;
4795     return true;
4796   }
4797
4798   // Continue promoting SExts if known as considerable depending on targets.
4799   if (ATPConsiderable &&
4800       performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4801                                   HasPromoted, TPT, SpeculativelyMovedExts))
4802     return true;
4803
4804   TPT.rollback(LastKnownGood);
4805   return false;
4806 }
4807
4808 // Perform address type promotion if doing so is profitable.
4809 // If AllowPromotionWithoutCommonHeader == false, we should find other sext
4810 // instructions that sign extended the same initial value. However, if
4811 // AllowPromotionWithoutCommonHeader == true, we expect promoting the
4812 // extension is just profitable.
4813 bool CodeGenPrepare::performAddressTypePromotion(
4814     Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
4815     bool HasPromoted, TypePromotionTransaction &TPT,
4816     SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
4817   bool Promoted = false;
4818   SmallPtrSet<Instruction *, 1> UnhandledExts;
4819   bool AllSeenFirst = true;
4820   for (auto I : SpeculativelyMovedExts) {
4821     Value *HeadOfChain = I->getOperand(0);
4822     DenseMap<Value *, Instruction *>::iterator AlreadySeen =
4823         SeenChainsForSExt.find(HeadOfChain);
4824     // If there is an unhandled SExt which has the same header, try to promote
4825     // it as well.
4826     if (AlreadySeen != SeenChainsForSExt.end()) {
4827       if (AlreadySeen->second != nullptr)
4828         UnhandledExts.insert(AlreadySeen->second);
4829       AllSeenFirst = false;
4830     }
4831   }
4832
4833   if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4834                         SpeculativelyMovedExts.size() == 1)) {
4835     TPT.commit();
4836     if (HasPromoted)
4837       Promoted = true;
4838     for (auto I : SpeculativelyMovedExts) {
4839       Value *HeadOfChain = I->getOperand(0);
4840       SeenChainsForSExt[HeadOfChain] = nullptr;
4841       ValToSExtendedUses[HeadOfChain].push_back(I);
4842     }
4843     // Update Inst as promotion happen.
4844     Inst = SpeculativelyMovedExts.pop_back_val();
4845   } else {
4846     // This is the first chain visited from the header, keep the current chain
4847     // as unhandled. Defer to promote this until we encounter another SExt
4848     // chain derived from the same header.
4849     for (auto I : SpeculativelyMovedExts) {
4850       Value *HeadOfChain = I->getOperand(0);
4851       SeenChainsForSExt[HeadOfChain] = Inst;
4852     }
4853     return false;
4854   }
4855
4856   if (!AllSeenFirst && !UnhandledExts.empty())
4857     for (auto VisitedSExt : UnhandledExts) {
4858       if (RemovedInsts.count(VisitedSExt))
4859         continue;
4860       TypePromotionTransaction TPT(RemovedInsts);
4861       SmallVector<Instruction *, 1> Exts;
4862       SmallVector<Instruction *, 2> Chains;
4863       Exts.push_back(VisitedSExt);
4864       bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4865       TPT.commit();
4866       if (HasPromoted)
4867         Promoted = true;
4868       for (auto I : Chains) {
4869         Value *HeadOfChain = I->getOperand(0);
4870         // Mark this as handled.
4871         SeenChainsForSExt[HeadOfChain] = nullptr;
4872         ValToSExtendedUses[HeadOfChain].push_back(I);
4873       }
4874     }
4875   return Promoted;
4876 }
4877
4878 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
4879   BasicBlock *DefBB = I->getParent();
4880
4881   // If the result of a {s|z}ext and its source are both live out, rewrite all
4882   // other uses of the source with result of extension.
4883   Value *Src = I->getOperand(0);
4884   if (Src->hasOneUse())
4885     return false;
4886
4887   // Only do this xform if truncating is free.
4888   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
4889     return false;
4890
4891   // Only safe to perform the optimization if the source is also defined in
4892   // this block.
4893   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
4894     return false;
4895
4896   bool DefIsLiveOut = false;
4897   for (User *U : I->users()) {
4898     Instruction *UI = cast<Instruction>(U);
4899
4900     // Figure out which BB this ext is used in.
4901     BasicBlock *UserBB = UI->getParent();
4902     if (UserBB == DefBB) continue;
4903     DefIsLiveOut = true;
4904     break;
4905   }
4906   if (!DefIsLiveOut)
4907     return false;
4908
4909   // Make sure none of the uses are PHI nodes.
4910   for (User *U : Src->users()) {
4911     Instruction *UI = cast<Instruction>(U);
4912     BasicBlock *UserBB = UI->getParent();
4913     if (UserBB == DefBB) continue;
4914     // Be conservative. We don't want this xform to end up introducing
4915     // reloads just before load / store instructions.
4916     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
4917       return false;
4918   }
4919
4920   // InsertedTruncs - Only insert one trunc in each block once.
4921   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4922
4923   bool MadeChange = false;
4924   for (Use &U : Src->uses()) {
4925     Instruction *User = cast<Instruction>(U.getUser());
4926
4927     // Figure out which BB this ext is used in.
4928     BasicBlock *UserBB = User->getParent();
4929     if (UserBB == DefBB) continue;
4930
4931     // Both src and def are live in this block. Rewrite the use.
4932     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4933
4934     if (!InsertedTrunc) {
4935       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
4936       assert(InsertPt != UserBB->end());
4937       InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
4938       InsertedInsts.insert(InsertedTrunc);
4939     }
4940
4941     // Replace a use of the {s|z}ext source with a use of the result.
4942     U = InsertedTrunc;
4943     ++NumExtUses;
4944     MadeChange = true;
4945   }
4946
4947   return MadeChange;
4948 }
4949
4950 // Find loads whose uses only use some of the loaded value's bits.  Add an "and"
4951 // just after the load if the target can fold this into one extload instruction,
4952 // with the hope of eliminating some of the other later "and" instructions using
4953 // the loaded value.  "and"s that are made trivially redundant by the insertion
4954 // of the new "and" are removed by this function, while others (e.g. those whose
4955 // path from the load goes through a phi) are left for isel to potentially
4956 // remove.
4957 //
4958 // For example:
4959 //
4960 // b0:
4961 //   x = load i32
4962 //   ...
4963 // b1:
4964 //   y = and x, 0xff
4965 //   z = use y
4966 //
4967 // becomes:
4968 //
4969 // b0:
4970 //   x = load i32
4971 //   x' = and x, 0xff
4972 //   ...
4973 // b1:
4974 //   z = use x'
4975 //
4976 // whereas:
4977 //
4978 // b0:
4979 //   x1 = load i32
4980 //   ...
4981 // b1:
4982 //   x2 = load i32
4983 //   ...
4984 // b2:
4985 //   x = phi x1, x2
4986 //   y = and x, 0xff
4987 //
4988 // becomes (after a call to optimizeLoadExt for each load):
4989 //
4990 // b0:
4991 //   x1 = load i32
4992 //   x1' = and x1, 0xff
4993 //   ...
4994 // b1:
4995 //   x2 = load i32
4996 //   x2' = and x2, 0xff
4997 //   ...
4998 // b2:
4999 //   x = phi x1', x2'
5000 //   y = and x, 0xff
5001 //
5002
5003 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5004
5005   if (!Load->isSimple() ||
5006       !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5007     return false;
5008
5009   // Skip loads we've already transformed.
5010   if (Load->hasOneUse() &&
5011       InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5012     return false;
5013
5014   // Look at all uses of Load, looking through phis, to determine how many bits
5015   // of the loaded value are needed.
5016   SmallVector<Instruction *, 8> WorkList;
5017   SmallPtrSet<Instruction *, 16> Visited;
5018   SmallVector<Instruction *, 8> AndsToMaybeRemove;
5019   for (auto *U : Load->users())
5020     WorkList.push_back(cast<Instruction>(U));
5021
5022   EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5023   unsigned BitWidth = LoadResultVT.getSizeInBits();
5024   APInt DemandBits(BitWidth, 0);
5025   APInt WidestAndBits(BitWidth, 0);
5026
5027   while (!WorkList.empty()) {
5028     Instruction *I = WorkList.back();
5029     WorkList.pop_back();
5030
5031     // Break use-def graph loops.
5032     if (!Visited.insert(I).second)
5033       continue;
5034
5035     // For a PHI node, push all of its users.
5036     if (auto *Phi = dyn_cast<PHINode>(I)) {
5037       for (auto *U : Phi->users())
5038         WorkList.push_back(cast<Instruction>(U));
5039       continue;
5040     }
5041
5042     switch (I->getOpcode()) {
5043     case llvm::Instruction::And: {
5044       auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5045       if (!AndC)
5046         return false;
5047       APInt AndBits = AndC->getValue();
5048       DemandBits |= AndBits;
5049       // Keep track of the widest and mask we see.
5050       if (AndBits.ugt(WidestAndBits))
5051         WidestAndBits = AndBits;
5052       if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5053         AndsToMaybeRemove.push_back(I);
5054       break;
5055     }
5056
5057     case llvm::Instruction::Shl: {
5058       auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5059       if (!ShlC)
5060         return false;
5061       uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5062       auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
5063       DemandBits |= ShlDemandBits;
5064       break;
5065     }
5066
5067     case llvm::Instruction::Trunc: {
5068       EVT TruncVT = TLI->getValueType(*DL, I->getType());
5069       unsigned TruncBitWidth = TruncVT.getSizeInBits();
5070       auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
5071       DemandBits |= TruncBits;
5072       break;
5073     }
5074
5075     default:
5076       return false;
5077     }
5078   }
5079
5080   uint32_t ActiveBits = DemandBits.getActiveBits();
5081   // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5082   // target even if isLoadExtLegal says an i1 EXTLOAD is valid.  For example,
5083   // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5084   // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5085   // followed by an AND.
5086   // TODO: Look into removing this restriction by fixing backends to either
5087   // return false for isLoadExtLegal for i1 or have them select this pattern to
5088   // a single instruction.
5089   //
5090   // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5091   // mask, since these are the only ands that will be removed by isel.
5092   if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
5093       WidestAndBits != DemandBits)
5094     return false;
5095
5096   LLVMContext &Ctx = Load->getType()->getContext();
5097   Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5098   EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5099
5100   // Reject cases that won't be matched as extloads.
5101   if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5102       !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5103     return false;
5104
5105   IRBuilder<> Builder(Load->getNextNode());
5106   auto *NewAnd = dyn_cast<Instruction>(
5107       Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5108   // Mark this instruction as "inserted by CGP", so that other
5109   // optimizations don't touch it.
5110   InsertedInsts.insert(NewAnd);
5111
5112   // Replace all uses of load with new and (except for the use of load in the
5113   // new and itself).
5114   Load->replaceAllUsesWith(NewAnd);
5115   NewAnd->setOperand(0, Load);
5116
5117   // Remove any and instructions that are now redundant.
5118   for (auto *And : AndsToMaybeRemove)
5119     // Check that the and mask is the same as the one we decided to put on the
5120     // new and.
5121     if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5122       And->replaceAllUsesWith(NewAnd);
5123       if (&*CurInstIterator == And)
5124         CurInstIterator = std::next(And->getIterator());
5125       And->eraseFromParent();
5126       ++NumAndUses;
5127     }
5128
5129   ++NumAndsAdded;
5130   return true;
5131 }
5132
5133 /// Check if V (an operand of a select instruction) is an expensive instruction
5134 /// that is only used once.
5135 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5136   auto *I = dyn_cast<Instruction>(V);
5137   // If it's safe to speculatively execute, then it should not have side
5138   // effects; therefore, it's safe to sink and possibly *not* execute.
5139   return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5140          TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5141 }
5142
5143 /// Returns true if a SelectInst should be turned into an explicit branch.
5144 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
5145                                                 const TargetLowering *TLI,
5146                                                 SelectInst *SI) {
5147   // If even a predictable select is cheap, then a branch can't be cheaper.
5148   if (!TLI->isPredictableSelectExpensive())
5149     return false;
5150
5151   // FIXME: This should use the same heuristics as IfConversion to determine
5152   // whether a select is better represented as a branch.
5153
5154   // If metadata tells us that the select condition is obviously predictable,
5155   // then we want to replace the select with a branch.
5156   uint64_t TrueWeight, FalseWeight;
5157   if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5158     uint64_t Max = std::max(TrueWeight, FalseWeight);
5159     uint64_t Sum = TrueWeight + FalseWeight;
5160     if (Sum != 0) {
5161       auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5162       if (Probability > TLI->getPredictableBranchThreshold())
5163         return true;
5164     }
5165   }
5166
5167   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5168
5169   // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5170   // comparison condition. If the compare has more than one use, there's
5171   // probably another cmov or setcc around, so it's not worth emitting a branch.
5172   if (!Cmp || !Cmp->hasOneUse())
5173     return false;
5174
5175   // If either operand of the select is expensive and only needed on one side
5176   // of the select, we should form a branch.
5177   if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5178       sinkSelectOperand(TTI, SI->getFalseValue()))
5179     return true;
5180
5181   return false;
5182 }
5183
5184 /// If \p isTrue is true, return the true value of \p SI, otherwise return
5185 /// false value of \p SI. If the true/false value of \p SI is defined by any
5186 /// select instructions in \p Selects, look through the defining select
5187 /// instruction until the true/false value is not defined in \p Selects.
5188 static Value *getTrueOrFalseValue(
5189     SelectInst *SI, bool isTrue,
5190     const SmallPtrSet<const Instruction *, 2> &Selects) {
5191   Value *V;
5192
5193   for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5194        DefSI = dyn_cast<SelectInst>(V)) {
5195     assert(DefSI->getCondition() == SI->getCondition() &&
5196            "The condition of DefSI does not match with SI");
5197     V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5198   }
5199   return V;
5200 }
5201
5202 /// If we have a SelectInst that will likely profit from branch prediction,
5203 /// turn it into a branch.
5204 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5205   // Find all consecutive select instructions that share the same condition.
5206   SmallVector<SelectInst *, 2> ASI;
5207   ASI.push_back(SI);
5208   for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5209        It != SI->getParent()->end(); ++It) {
5210     SelectInst *I = dyn_cast<SelectInst>(&*It);
5211     if (I && SI->getCondition() == I->getCondition()) {
5212       ASI.push_back(I);
5213     } else {
5214       break;
5215     }
5216   }
5217
5218   SelectInst *LastSI = ASI.back();
5219   // Increment the current iterator to skip all the rest of select instructions
5220   // because they will be either "not lowered" or "all lowered" to branch.
5221   CurInstIterator = std::next(LastSI->getIterator());
5222
5223   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5224
5225   // Can we convert the 'select' to CF ?
5226   if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5227       SI->getMetadata(LLVMContext::MD_unpredictable))
5228     return false;
5229
5230   TargetLowering::SelectSupportKind SelectKind;
5231   if (VectorCond)
5232     SelectKind = TargetLowering::VectorMaskSelect;
5233   else if (SI->getType()->isVectorTy())
5234     SelectKind = TargetLowering::ScalarCondVectorVal;
5235   else
5236     SelectKind = TargetLowering::ScalarValSelect;
5237
5238   if (TLI->isSelectSupported(SelectKind) &&
5239       !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5240     return false;
5241
5242   ModifiedDT = true;
5243
5244   // Transform a sequence like this:
5245   //    start:
5246   //       %cmp = cmp uge i32 %a, %b
5247   //       %sel = select i1 %cmp, i32 %c, i32 %d
5248   //
5249   // Into:
5250   //    start:
5251   //       %cmp = cmp uge i32 %a, %b
5252   //       br i1 %cmp, label %select.true, label %select.false
5253   //    select.true:
5254   //       br label %select.end
5255   //    select.false:
5256   //       br label %select.end
5257   //    select.end:
5258   //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5259   //
5260   // In addition, we may sink instructions that produce %c or %d from
5261   // the entry block into the destination(s) of the new branch.
5262   // If the true or false blocks do not contain a sunken instruction, that
5263   // block and its branch may be optimized away. In that case, one side of the
5264   // first branch will point directly to select.end, and the corresponding PHI
5265   // predecessor block will be the start block.
5266
5267   // First, we split the block containing the select into 2 blocks.
5268   BasicBlock *StartBlock = SI->getParent();
5269   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
5270   BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
5271
5272   // Delete the unconditional branch that was just created by the split.
5273   StartBlock->getTerminator()->eraseFromParent();
5274
5275   // These are the new basic blocks for the conditional branch.
5276   // At least one will become an actual new basic block.
5277   BasicBlock *TrueBlock = nullptr;
5278   BasicBlock *FalseBlock = nullptr;
5279   BranchInst *TrueBranch = nullptr;
5280   BranchInst *FalseBranch = nullptr;
5281
5282   // Sink expensive instructions into the conditional blocks to avoid executing
5283   // them speculatively.
5284   for (SelectInst *SI : ASI) {
5285     if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5286       if (TrueBlock == nullptr) {
5287         TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5288                                        EndBlock->getParent(), EndBlock);
5289         TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5290       }
5291       auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5292       TrueInst->moveBefore(TrueBranch);
5293     }
5294     if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5295       if (FalseBlock == nullptr) {
5296         FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5297                                         EndBlock->getParent(), EndBlock);
5298         FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5299       }
5300       auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5301       FalseInst->moveBefore(FalseBranch);
5302     }
5303   }
5304
5305   // If there was nothing to sink, then arbitrarily choose the 'false' side
5306   // for a new input value to the PHI.
5307   if (TrueBlock == FalseBlock) {
5308     assert(TrueBlock == nullptr &&
5309            "Unexpected basic block transform while optimizing select");
5310
5311     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5312                                     EndBlock->getParent(), EndBlock);
5313     BranchInst::Create(EndBlock, FalseBlock);
5314   }
5315
5316   // Insert the real conditional branch based on the original condition.
5317   // If we did not create a new block for one of the 'true' or 'false' paths
5318   // of the condition, it means that side of the branch goes to the end block
5319   // directly and the path originates from the start block from the point of
5320   // view of the new PHI.
5321   BasicBlock *TT, *FT;
5322   if (TrueBlock == nullptr) {
5323     TT = EndBlock;
5324     FT = FalseBlock;
5325     TrueBlock = StartBlock;
5326   } else if (FalseBlock == nullptr) {
5327     TT = TrueBlock;
5328     FT = EndBlock;
5329     FalseBlock = StartBlock;
5330   } else {
5331     TT = TrueBlock;
5332     FT = FalseBlock;
5333   }
5334   IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
5335
5336   SmallPtrSet<const Instruction *, 2> INS;
5337   INS.insert(ASI.begin(), ASI.end());
5338   // Use reverse iterator because later select may use the value of the
5339   // earlier select, and we need to propagate value through earlier select
5340   // to get the PHI operand.
5341   for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5342     SelectInst *SI = *It;
5343     // The select itself is replaced with a PHI Node.
5344     PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5345     PN->takeName(SI);
5346     PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5347     PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
5348
5349     SI->replaceAllUsesWith(PN);
5350     SI->eraseFromParent();
5351     INS.erase(SI);
5352     ++NumSelectsExpanded;
5353   }
5354
5355   // Instruct OptimizeBlock to skip to the next block.
5356   CurInstIterator = StartBlock->end();
5357   return true;
5358 }
5359
5360 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
5361   SmallVector<int, 16> Mask(SVI->getShuffleMask());
5362   int SplatElem = -1;
5363   for (unsigned i = 0; i < Mask.size(); ++i) {
5364     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5365       return false;
5366     SplatElem = Mask[i];
5367   }
5368
5369   return true;
5370 }
5371
5372 /// Some targets have expensive vector shifts if the lanes aren't all the same
5373 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5374 /// it's often worth sinking a shufflevector splat down to its use so that
5375 /// codegen can spot all lanes are identical.
5376 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
5377   BasicBlock *DefBB = SVI->getParent();
5378
5379   // Only do this xform if variable vector shifts are particularly expensive.
5380   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5381     return false;
5382
5383   // We only expect better codegen by sinking a shuffle if we can recognise a
5384   // constant splat.
5385   if (!isBroadcastShuffle(SVI))
5386     return false;
5387
5388   // InsertedShuffles - Only insert a shuffle in each block once.
5389   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5390
5391   bool MadeChange = false;
5392   for (User *U : SVI->users()) {
5393     Instruction *UI = cast<Instruction>(U);
5394
5395     // Figure out which BB this ext is used in.
5396     BasicBlock *UserBB = UI->getParent();
5397     if (UserBB == DefBB) continue;
5398
5399     // For now only apply this when the splat is used by a shift instruction.
5400     if (!UI->isShift()) continue;
5401
5402     // Everything checks out, sink the shuffle if the user's block doesn't
5403     // already have a copy.
5404     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5405
5406     if (!InsertedShuffle) {
5407       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5408       assert(InsertPt != UserBB->end());
5409       InsertedShuffle =
5410           new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5411                                 SVI->getOperand(2), "", &*InsertPt);
5412     }
5413
5414     UI->replaceUsesOfWith(SVI, InsertedShuffle);
5415     MadeChange = true;
5416   }
5417
5418   // If we removed all uses, nuke the shuffle.
5419   if (SVI->use_empty()) {
5420     SVI->eraseFromParent();
5421     MadeChange = true;
5422   }
5423
5424   return MadeChange;
5425 }
5426
5427 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5428   if (!TLI || !DL)
5429     return false;
5430
5431   Value *Cond = SI->getCondition();
5432   Type *OldType = Cond->getType();
5433   LLVMContext &Context = Cond->getContext();
5434   MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5435   unsigned RegWidth = RegType.getSizeInBits();
5436
5437   if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5438     return false;
5439
5440   // If the register width is greater than the type width, expand the condition
5441   // of the switch instruction and each case constant to the width of the
5442   // register. By widening the type of the switch condition, subsequent
5443   // comparisons (for case comparisons) will not need to be extended to the
5444   // preferred register width, so we will potentially eliminate N-1 extends,
5445   // where N is the number of cases in the switch.
5446   auto *NewType = Type::getIntNTy(Context, RegWidth);
5447
5448   // Zero-extend the switch condition and case constants unless the switch
5449   // condition is a function argument that is already being sign-extended.
5450   // In that case, we can avoid an unnecessary mask/extension by sign-extending
5451   // everything instead.
5452   Instruction::CastOps ExtType = Instruction::ZExt;
5453   if (auto *Arg = dyn_cast<Argument>(Cond))
5454     if (Arg->hasSExtAttr())
5455       ExtType = Instruction::SExt;
5456
5457   auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5458   ExtInst->insertBefore(SI);
5459   SI->setCondition(ExtInst);
5460   for (auto Case : SI->cases()) {
5461     APInt NarrowConst = Case.getCaseValue()->getValue();
5462     APInt WideConst = (ExtType == Instruction::ZExt) ?
5463                       NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5464     Case.setValue(ConstantInt::get(Context, WideConst));
5465   }
5466
5467   return true;
5468 }
5469
5470 namespace {
5471 /// \brief Helper class to promote a scalar operation to a vector one.
5472 /// This class is used to move downward extractelement transition.
5473 /// E.g.,
5474 /// a = vector_op <2 x i32>
5475 /// b = extractelement <2 x i32> a, i32 0
5476 /// c = scalar_op b
5477 /// store c
5478 ///
5479 /// =>
5480 /// a = vector_op <2 x i32>
5481 /// c = vector_op a (equivalent to scalar_op on the related lane)
5482 /// * d = extractelement <2 x i32> c, i32 0
5483 /// * store d
5484 /// Assuming both extractelement and store can be combine, we get rid of the
5485 /// transition.
5486 class VectorPromoteHelper {
5487   /// DataLayout associated with the current module.
5488   const DataLayout &DL;
5489
5490   /// Used to perform some checks on the legality of vector operations.
5491   const TargetLowering &TLI;
5492
5493   /// Used to estimated the cost of the promoted chain.
5494   const TargetTransformInfo &TTI;
5495
5496   /// The transition being moved downwards.
5497   Instruction *Transition;
5498   /// The sequence of instructions to be promoted.
5499   SmallVector<Instruction *, 4> InstsToBePromoted;
5500   /// Cost of combining a store and an extract.
5501   unsigned StoreExtractCombineCost;
5502   /// Instruction that will be combined with the transition.
5503   Instruction *CombineInst;
5504
5505   /// \brief The instruction that represents the current end of the transition.
5506   /// Since we are faking the promotion until we reach the end of the chain
5507   /// of computation, we need a way to get the current end of the transition.
5508   Instruction *getEndOfTransition() const {
5509     if (InstsToBePromoted.empty())
5510       return Transition;
5511     return InstsToBePromoted.back();
5512   }
5513
5514   /// \brief Return the index of the original value in the transition.
5515   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5516   /// c, is at index 0.
5517   unsigned getTransitionOriginalValueIdx() const {
5518     assert(isa<ExtractElementInst>(Transition) &&
5519            "Other kind of transitions are not supported yet");
5520     return 0;
5521   }
5522
5523   /// \brief Return the index of the index in the transition.
5524   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5525   /// is at index 1.
5526   unsigned getTransitionIdx() const {
5527     assert(isa<ExtractElementInst>(Transition) &&
5528            "Other kind of transitions are not supported yet");
5529     return 1;
5530   }
5531
5532   /// \brief Get the type of the transition.
5533   /// This is the type of the original value.
5534   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5535   /// transition is <2 x i32>.
5536   Type *getTransitionType() const {
5537     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5538   }
5539
5540   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5541   /// I.e., we have the following sequence:
5542   /// Def = Transition <ty1> a to <ty2>
5543   /// b = ToBePromoted <ty2> Def, ...
5544   /// =>
5545   /// b = ToBePromoted <ty1> a, ...
5546   /// Def = Transition <ty1> ToBePromoted to <ty2>
5547   void promoteImpl(Instruction *ToBePromoted);
5548
5549   /// \brief Check whether or not it is profitable to promote all the
5550   /// instructions enqueued to be promoted.
5551   bool isProfitableToPromote() {
5552     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5553     unsigned Index = isa<ConstantInt>(ValIdx)
5554                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
5555                          : -1;
5556     Type *PromotedType = getTransitionType();
5557
5558     StoreInst *ST = cast<StoreInst>(CombineInst);
5559     unsigned AS = ST->getPointerAddressSpace();
5560     unsigned Align = ST->getAlignment();
5561     // Check if this store is supported.
5562     if (!TLI.allowsMisalignedMemoryAccesses(
5563             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5564             Align)) {
5565       // If this is not supported, there is no way we can combine
5566       // the extract with the store.
5567       return false;
5568     }
5569
5570     // The scalar chain of computation has to pay for the transition
5571     // scalar to vector.
5572     // The vector chain has to account for the combining cost.
5573     uint64_t ScalarCost =
5574         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5575     uint64_t VectorCost = StoreExtractCombineCost;
5576     for (const auto &Inst : InstsToBePromoted) {
5577       // Compute the cost.
5578       // By construction, all instructions being promoted are arithmetic ones.
5579       // Moreover, one argument is a constant that can be viewed as a splat
5580       // constant.
5581       Value *Arg0 = Inst->getOperand(0);
5582       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5583                             isa<ConstantFP>(Arg0);
5584       TargetTransformInfo::OperandValueKind Arg0OVK =
5585           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5586                          : TargetTransformInfo::OK_AnyValue;
5587       TargetTransformInfo::OperandValueKind Arg1OVK =
5588           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5589                           : TargetTransformInfo::OK_AnyValue;
5590       ScalarCost += TTI.getArithmeticInstrCost(
5591           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5592       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5593                                                Arg0OVK, Arg1OVK);
5594     }
5595     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5596                  << ScalarCost << "\nVector: " << VectorCost << '\n');
5597     return ScalarCost > VectorCost;
5598   }
5599
5600   /// \brief Generate a constant vector with \p Val with the same
5601   /// number of elements as the transition.
5602   /// \p UseSplat defines whether or not \p Val should be replicated
5603   /// across the whole vector.
5604   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5605   /// otherwise we generate a vector with as many undef as possible:
5606   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5607   /// used at the index of the extract.
5608   Value *getConstantVector(Constant *Val, bool UseSplat) const {
5609     unsigned ExtractIdx = UINT_MAX;
5610     if (!UseSplat) {
5611       // If we cannot determine where the constant must be, we have to
5612       // use a splat constant.
5613       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5614       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5615         ExtractIdx = CstVal->getSExtValue();
5616       else
5617         UseSplat = true;
5618     }
5619
5620     unsigned End = getTransitionType()->getVectorNumElements();
5621     if (UseSplat)
5622       return ConstantVector::getSplat(End, Val);
5623
5624     SmallVector<Constant *, 4> ConstVec;
5625     UndefValue *UndefVal = UndefValue::get(Val->getType());
5626     for (unsigned Idx = 0; Idx != End; ++Idx) {
5627       if (Idx == ExtractIdx)
5628         ConstVec.push_back(Val);
5629       else
5630         ConstVec.push_back(UndefVal);
5631     }
5632     return ConstantVector::get(ConstVec);
5633   }
5634
5635   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5636   /// in \p Use can trigger undefined behavior.
5637   static bool canCauseUndefinedBehavior(const Instruction *Use,
5638                                         unsigned OperandIdx) {
5639     // This is not safe to introduce undef when the operand is on
5640     // the right hand side of a division-like instruction.
5641     if (OperandIdx != 1)
5642       return false;
5643     switch (Use->getOpcode()) {
5644     default:
5645       return false;
5646     case Instruction::SDiv:
5647     case Instruction::UDiv:
5648     case Instruction::SRem:
5649     case Instruction::URem:
5650       return true;
5651     case Instruction::FDiv:
5652     case Instruction::FRem:
5653       return !Use->hasNoNaNs();
5654     }
5655     llvm_unreachable(nullptr);
5656   }
5657
5658 public:
5659   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5660                       const TargetTransformInfo &TTI, Instruction *Transition,
5661                       unsigned CombineCost)
5662       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
5663         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5664     assert(Transition && "Do not know how to promote null");
5665   }
5666
5667   /// \brief Check if we can promote \p ToBePromoted to \p Type.
5668   bool canPromote(const Instruction *ToBePromoted) const {
5669     // We could support CastInst too.
5670     return isa<BinaryOperator>(ToBePromoted);
5671   }
5672
5673   /// \brief Check if it is profitable to promote \p ToBePromoted
5674   /// by moving downward the transition through.
5675   bool shouldPromote(const Instruction *ToBePromoted) const {
5676     // Promote only if all the operands can be statically expanded.
5677     // Indeed, we do not want to introduce any new kind of transitions.
5678     for (const Use &U : ToBePromoted->operands()) {
5679       const Value *Val = U.get();
5680       if (Val == getEndOfTransition()) {
5681         // If the use is a division and the transition is on the rhs,
5682         // we cannot promote the operation, otherwise we may create a
5683         // division by zero.
5684         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5685           return false;
5686         continue;
5687       }
5688       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5689           !isa<ConstantFP>(Val))
5690         return false;
5691     }
5692     // Check that the resulting operation is legal.
5693     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5694     if (!ISDOpcode)
5695       return false;
5696     return StressStoreExtract ||
5697            TLI.isOperationLegalOrCustom(
5698                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
5699   }
5700
5701   /// \brief Check whether or not \p Use can be combined
5702   /// with the transition.
5703   /// I.e., is it possible to do Use(Transition) => AnotherUse?
5704   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5705
5706   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5707   void enqueueForPromotion(Instruction *ToBePromoted) {
5708     InstsToBePromoted.push_back(ToBePromoted);
5709   }
5710
5711   /// \brief Set the instruction that will be combined with the transition.
5712   void recordCombineInstruction(Instruction *ToBeCombined) {
5713     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5714     CombineInst = ToBeCombined;
5715   }
5716
5717   /// \brief Promote all the instructions enqueued for promotion if it is
5718   /// is profitable.
5719   /// \return True if the promotion happened, false otherwise.
5720   bool promote() {
5721     // Check if there is something to promote.
5722     // Right now, if we do not have anything to combine with,
5723     // we assume the promotion is not profitable.
5724     if (InstsToBePromoted.empty() || !CombineInst)
5725       return false;
5726
5727     // Check cost.
5728     if (!StressStoreExtract && !isProfitableToPromote())
5729       return false;
5730
5731     // Promote.
5732     for (auto &ToBePromoted : InstsToBePromoted)
5733       promoteImpl(ToBePromoted);
5734     InstsToBePromoted.clear();
5735     return true;
5736   }
5737 };
5738 } // End of anonymous namespace.
5739
5740 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5741   // At this point, we know that all the operands of ToBePromoted but Def
5742   // can be statically promoted.
5743   // For Def, we need to use its parameter in ToBePromoted:
5744   // b = ToBePromoted ty1 a
5745   // Def = Transition ty1 b to ty2
5746   // Move the transition down.
5747   // 1. Replace all uses of the promoted operation by the transition.
5748   // = ... b => = ... Def.
5749   assert(ToBePromoted->getType() == Transition->getType() &&
5750          "The type of the result of the transition does not match "
5751          "the final type");
5752   ToBePromoted->replaceAllUsesWith(Transition);
5753   // 2. Update the type of the uses.
5754   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5755   Type *TransitionTy = getTransitionType();
5756   ToBePromoted->mutateType(TransitionTy);
5757   // 3. Update all the operands of the promoted operation with promoted
5758   // operands.
5759   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5760   for (Use &U : ToBePromoted->operands()) {
5761     Value *Val = U.get();
5762     Value *NewVal = nullptr;
5763     if (Val == Transition)
5764       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5765     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5766              isa<ConstantFP>(Val)) {
5767       // Use a splat constant if it is not safe to use undef.
5768       NewVal = getConstantVector(
5769           cast<Constant>(Val),
5770           isa<UndefValue>(Val) ||
5771               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5772     } else
5773       llvm_unreachable("Did you modified shouldPromote and forgot to update "
5774                        "this?");
5775     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5776   }
5777   Transition->removeFromParent();
5778   Transition->insertAfter(ToBePromoted);
5779   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5780 }
5781
5782 /// Some targets can do store(extractelement) with one instruction.
5783 /// Try to push the extractelement towards the stores when the target
5784 /// has this feature and this is profitable.
5785 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
5786   unsigned CombineCost = UINT_MAX;
5787   if (DisableStoreExtract || !TLI ||
5788       (!StressStoreExtract &&
5789        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5790                                        Inst->getOperand(1), CombineCost)))
5791     return false;
5792
5793   // At this point we know that Inst is a vector to scalar transition.
5794   // Try to move it down the def-use chain, until:
5795   // - We can combine the transition with its single use
5796   //   => we got rid of the transition.
5797   // - We escape the current basic block
5798   //   => we would need to check that we are moving it at a cheaper place and
5799   //      we do not do that for now.
5800   BasicBlock *Parent = Inst->getParent();
5801   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
5802   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
5803   // If the transition has more than one use, assume this is not going to be
5804   // beneficial.
5805   while (Inst->hasOneUse()) {
5806     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5807     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5808
5809     if (ToBePromoted->getParent() != Parent) {
5810       DEBUG(dbgs() << "Instruction to promote is in a different block ("
5811                    << ToBePromoted->getParent()->getName()
5812                    << ") than the transition (" << Parent->getName() << ").\n");
5813       return false;
5814     }
5815
5816     if (VPH.canCombine(ToBePromoted)) {
5817       DEBUG(dbgs() << "Assume " << *Inst << '\n'
5818                    << "will be combined with: " << *ToBePromoted << '\n');
5819       VPH.recordCombineInstruction(ToBePromoted);
5820       bool Changed = VPH.promote();
5821       NumStoreExtractExposed += Changed;
5822       return Changed;
5823     }
5824
5825     DEBUG(dbgs() << "Try promoting.\n");
5826     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5827       return false;
5828
5829     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5830
5831     VPH.enqueueForPromotion(ToBePromoted);
5832     Inst = ToBePromoted;
5833   }
5834   return false;
5835 }
5836
5837 /// For the instruction sequence of store below, F and I values
5838 /// are bundled together as an i64 value before being stored into memory.
5839 /// Sometimes it is more efficent to generate separate stores for F and I,
5840 /// which can remove the bitwise instructions or sink them to colder places.
5841 ///
5842 ///   (store (or (zext (bitcast F to i32) to i64),
5843 ///              (shl (zext I to i64), 32)), addr)  -->
5844 ///   (store F, addr) and (store I, addr+4)
5845 ///
5846 /// Similarly, splitting for other merged store can also be beneficial, like:
5847 /// For pair of {i32, i32}, i64 store --> two i32 stores.
5848 /// For pair of {i32, i16}, i64 store --> two i32 stores.
5849 /// For pair of {i16, i16}, i32 store --> two i16 stores.
5850 /// For pair of {i16, i8},  i32 store --> two i16 stores.
5851 /// For pair of {i8, i8},   i16 store --> two i8 stores.
5852 ///
5853 /// We allow each target to determine specifically which kind of splitting is
5854 /// supported.
5855 ///
5856 /// The store patterns are commonly seen from the simple code snippet below
5857 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5858 ///   void goo(const std::pair<int, float> &);
5859 ///   hoo() {
5860 ///     ...
5861 ///     goo(std::make_pair(tmp, ftmp));
5862 ///     ...
5863 ///   }
5864 ///
5865 /// Although we already have similar splitting in DAG Combine, we duplicate
5866 /// it in CodeGenPrepare to catch the case in which pattern is across
5867 /// multiple BBs. The logic in DAG Combine is kept to catch case generated
5868 /// during code expansion.
5869 static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5870                                 const TargetLowering &TLI) {
5871   // Handle simple but common cases only.
5872   Type *StoreType = SI.getValueOperand()->getType();
5873   if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5874       DL.getTypeSizeInBits(StoreType) == 0)
5875     return false;
5876
5877   unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5878   Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5879   if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5880       DL.getTypeSizeInBits(SplitStoreType))
5881     return false;
5882
5883   // Match the following patterns:
5884   // (store (or (zext LValue to i64),
5885   //            (shl (zext HValue to i64), 32)), HalfValBitSize)
5886   //  or
5887   // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5888   //            (zext LValue to i64),
5889   // Expect both operands of OR and the first operand of SHL have only
5890   // one use.
5891   Value *LValue, *HValue;
5892   if (!match(SI.getValueOperand(),
5893              m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5894                     m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5895                                    m_SpecificInt(HalfValBitSize))))))
5896     return false;
5897
5898   // Check LValue and HValue are int with size less or equal than 32.
5899   if (!LValue->getType()->isIntegerTy() ||
5900       DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5901       !HValue->getType()->isIntegerTy() ||
5902       DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5903     return false;
5904
5905   // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5906   // as the input of target query.
5907   auto *LBC = dyn_cast<BitCastInst>(LValue);
5908   auto *HBC = dyn_cast<BitCastInst>(HValue);
5909   EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5910                   : EVT::getEVT(LValue->getType());
5911   EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5912                    : EVT::getEVT(HValue->getType());
5913   if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5914     return false;
5915
5916   // Start to split store.
5917   IRBuilder<> Builder(SI.getContext());
5918   Builder.SetInsertPoint(&SI);
5919
5920   // If LValue/HValue is a bitcast in another BB, create a new one in current
5921   // BB so it may be merged with the splitted stores by dag combiner.
5922   if (LBC && LBC->getParent() != SI.getParent())
5923     LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5924   if (HBC && HBC->getParent() != SI.getParent())
5925     HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
5926
5927   auto CreateSplitStore = [&](Value *V, bool Upper) {
5928     V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
5929     Value *Addr = Builder.CreateBitCast(
5930         SI.getOperand(1),
5931         SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
5932     if (Upper)
5933       Addr = Builder.CreateGEP(
5934           SplitStoreType, Addr,
5935           ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
5936     Builder.CreateAlignedStore(
5937         V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
5938   };
5939
5940   CreateSplitStore(LValue, false);
5941   CreateSplitStore(HValue, true);
5942
5943   // Delete the old store.
5944   SI.eraseFromParent();
5945   return true;
5946 }
5947
5948 bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
5949   // Bail out if we inserted the instruction to prevent optimizations from
5950   // stepping on each other's toes.
5951   if (InsertedInsts.count(I))
5952     return false;
5953
5954   if (PHINode *P = dyn_cast<PHINode>(I)) {
5955     // It is possible for very late stage optimizations (such as SimplifyCFG)
5956     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
5957     // trivial PHI, go ahead and zap it here.
5958     if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
5959       P->replaceAllUsesWith(V);
5960       P->eraseFromParent();
5961       ++NumPHIsElim;
5962       return true;
5963     }
5964     return false;
5965   }
5966
5967   if (CastInst *CI = dyn_cast<CastInst>(I)) {
5968     // If the source of the cast is a constant, then this should have
5969     // already been constant folded.  The only reason NOT to constant fold
5970     // it is if something (e.g. LSR) was careful to place the constant
5971     // evaluation in a block other than then one that uses it (e.g. to hoist
5972     // the address of globals out of a loop).  If this is the case, we don't
5973     // want to forward-subst the cast.
5974     if (isa<Constant>(CI->getOperand(0)))
5975       return false;
5976
5977     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
5978       return true;
5979
5980     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
5981       /// Sink a zext or sext into its user blocks if the target type doesn't
5982       /// fit in one register
5983       if (TLI &&
5984           TLI->getTypeAction(CI->getContext(),
5985                              TLI->getValueType(*DL, CI->getType())) ==
5986               TargetLowering::TypeExpandInteger) {
5987         return SinkCast(CI);
5988       } else {
5989         bool MadeChange = optimizeExt(I);
5990         return MadeChange | optimizeExtUses(I);
5991       }
5992     }
5993     return false;
5994   }
5995
5996   if (CmpInst *CI = dyn_cast<CmpInst>(I))
5997     if (!TLI || !TLI->hasMultipleConditionRegisters())
5998       return OptimizeCmpExpression(CI, TLI);
5999
6000   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6001     LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
6002     if (TLI) {
6003       bool Modified = optimizeLoadExt(LI);
6004       unsigned AS = LI->getPointerAddressSpace();
6005       Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6006       return Modified;
6007     }
6008     return false;
6009   }
6010
6011   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6012     if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6013       return true;
6014     SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
6015     if (TLI) {
6016       unsigned AS = SI->getPointerAddressSpace();
6017       return optimizeMemoryInst(I, SI->getOperand(1),
6018                                 SI->getOperand(0)->getType(), AS);
6019     }
6020     return false;
6021   }
6022
6023   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6024       unsigned AS = RMW->getPointerAddressSpace();
6025       return optimizeMemoryInst(I, RMW->getPointerOperand(),
6026                                 RMW->getType(), AS);
6027   }
6028
6029   if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6030       unsigned AS = CmpX->getPointerAddressSpace();
6031       return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6032                                 CmpX->getCompareOperand()->getType(), AS);
6033   }
6034
6035   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6036
6037   if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6038       EnableAndCmpSinking && TLI)
6039     return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6040
6041   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6042                 BinOp->getOpcode() == Instruction::LShr)) {
6043     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6044     if (TLI && CI && TLI->hasExtractBitsInsn())
6045       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
6046
6047     return false;
6048   }
6049
6050   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
6051     if (GEPI->hasAllZeroIndices()) {
6052       /// The GEP operand must be a pointer, so must its result -> BitCast
6053       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6054                                         GEPI->getName(), GEPI);
6055       GEPI->replaceAllUsesWith(NC);
6056       GEPI->eraseFromParent();
6057       ++NumGEPsElim;
6058       optimizeInst(NC, ModifiedDT);
6059       return true;
6060     }
6061     return false;
6062   }
6063
6064   if (CallInst *CI = dyn_cast<CallInst>(I))
6065     return optimizeCallInst(CI, ModifiedDT);
6066
6067   if (SelectInst *SI = dyn_cast<SelectInst>(I))
6068     return optimizeSelectInst(SI);
6069
6070   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
6071     return optimizeShuffleVectorInst(SVI);
6072
6073   if (auto *Switch = dyn_cast<SwitchInst>(I))
6074     return optimizeSwitchInst(Switch);
6075
6076   if (isa<ExtractElementInst>(I))
6077     return optimizeExtractElementInst(I);
6078
6079   return false;
6080 }
6081
6082 /// Given an OR instruction, check to see if this is a bitreverse
6083 /// idiom. If so, insert the new intrinsic and return true.
6084 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6085                            const TargetLowering &TLI) {
6086   if (!I.getType()->isIntegerTy() ||
6087       !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6088                                     TLI.getValueType(DL, I.getType(), true)))
6089     return false;
6090
6091   SmallVector<Instruction*, 4> Insts;
6092   if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
6093     return false;
6094   Instruction *LastInst = Insts.back();
6095   I.replaceAllUsesWith(LastInst);
6096   RecursivelyDeleteTriviallyDeadInstructions(&I);
6097   return true;
6098 }
6099
6100 // In this pass we look for GEP and cast instructions that are used
6101 // across basic blocks and rewrite them to improve basic-block-at-a-time
6102 // selection.
6103 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
6104   SunkAddrs.clear();
6105   bool MadeChange = false;
6106
6107   CurInstIterator = BB.begin();
6108   while (CurInstIterator != BB.end()) {
6109     MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6110     if (ModifiedDT)
6111       return true;
6112   }
6113
6114   bool MadeBitReverse = true;
6115   while (TLI && MadeBitReverse) {
6116     MadeBitReverse = false;
6117     for (auto &I : reverse(BB)) {
6118       if (makeBitReverse(I, *DL, *TLI)) {
6119         MadeBitReverse = MadeChange = true;
6120         ModifiedDT = true;
6121         break;
6122       }
6123     }
6124   }
6125   MadeChange |= dupRetToEnableTailCallOpts(&BB);
6126
6127   return MadeChange;
6128 }
6129
6130 // llvm.dbg.value is far away from the value then iSel may not be able
6131 // handle it properly. iSel will drop llvm.dbg.value if it can not
6132 // find a node corresponding to the value.
6133 bool CodeGenPrepare::placeDbgValues(Function &F) {
6134   bool MadeChange = false;
6135   for (BasicBlock &BB : F) {
6136     Instruction *PrevNonDbgInst = nullptr;
6137     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
6138       Instruction *Insn = &*BI++;
6139       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
6140       // Leave dbg.values that refer to an alloca alone. These
6141       // instrinsics describe the address of a variable (= the alloca)
6142       // being taken.  They should not be moved next to the alloca
6143       // (and to the beginning of the scope), but rather stay close to
6144       // where said address is used.
6145       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
6146         PrevNonDbgInst = Insn;
6147         continue;
6148       }
6149
6150       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6151       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
6152         // If VI is a phi in a block with an EHPad terminator, we can't insert
6153         // after it.
6154         if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6155           continue;
6156         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6157         DVI->removeFromParent();
6158         if (isa<PHINode>(VI))
6159           DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6160         else
6161           DVI->insertAfter(VI);
6162         MadeChange = true;
6163         ++NumDbgValueMoved;
6164       }
6165     }
6166   }
6167   return MadeChange;
6168 }
6169
6170 /// \brief Scale down both weights to fit into uint32_t.
6171 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6172   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6173   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
6174   NewTrue = NewTrue / Scale;
6175   NewFalse = NewFalse / Scale;
6176 }
6177
6178 /// \brief Some targets prefer to split a conditional branch like:
6179 /// \code
6180 ///   %0 = icmp ne i32 %a, 0
6181 ///   %1 = icmp ne i32 %b, 0
6182 ///   %or.cond = or i1 %0, %1
6183 ///   br i1 %or.cond, label %TrueBB, label %FalseBB
6184 /// \endcode
6185 /// into multiple branch instructions like:
6186 /// \code
6187 ///   bb1:
6188 ///     %0 = icmp ne i32 %a, 0
6189 ///     br i1 %0, label %TrueBB, label %bb2
6190 ///   bb2:
6191 ///     %1 = icmp ne i32 %b, 0
6192 ///     br i1 %1, label %TrueBB, label %FalseBB
6193 /// \endcode
6194 /// This usually allows instruction selection to do even further optimizations
6195 /// and combine the compare with the branch instruction. Currently this is
6196 /// applied for targets which have "cheap" jump instructions.
6197 ///
6198 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6199 ///
6200 bool CodeGenPrepare::splitBranchCondition(Function &F) {
6201   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
6202     return false;
6203
6204   bool MadeChange = false;
6205   for (auto &BB : F) {
6206     // Does this BB end with the following?
6207     //   %cond1 = icmp|fcmp|binary instruction ...
6208     //   %cond2 = icmp|fcmp|binary instruction ...
6209     //   %cond.or = or|and i1 %cond1, cond2
6210     //   br i1 %cond.or label %dest1, label %dest2"
6211     BinaryOperator *LogicOp;
6212     BasicBlock *TBB, *FBB;
6213     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6214       continue;
6215
6216     auto *Br1 = cast<BranchInst>(BB.getTerminator());
6217     if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6218       continue;
6219
6220     unsigned Opc;
6221     Value *Cond1, *Cond2;
6222     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6223                              m_OneUse(m_Value(Cond2)))))
6224       Opc = Instruction::And;
6225     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6226                                  m_OneUse(m_Value(Cond2)))))
6227       Opc = Instruction::Or;
6228     else
6229       continue;
6230
6231     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6232         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
6233       continue;
6234
6235     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6236
6237     // Create a new BB.
6238     auto TmpBB =
6239         BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6240                            BB.getParent(), BB.getNextNode());
6241
6242     // Update original basic block by using the first condition directly by the
6243     // branch instruction and removing the no longer needed and/or instruction.
6244     Br1->setCondition(Cond1);
6245     LogicOp->eraseFromParent();
6246
6247     // Depending on the conditon we have to either replace the true or the false
6248     // successor of the original branch instruction.
6249     if (Opc == Instruction::And)
6250       Br1->setSuccessor(0, TmpBB);
6251     else
6252       Br1->setSuccessor(1, TmpBB);
6253
6254     // Fill in the new basic block.
6255     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6256     if (auto *I = dyn_cast<Instruction>(Cond2)) {
6257       I->removeFromParent();
6258       I->insertBefore(Br2);
6259     }
6260
6261     // Update PHI nodes in both successors. The original BB needs to be
6262     // replaced in one succesor's PHI nodes, because the branch comes now from
6263     // the newly generated BB (NewBB). In the other successor we need to add one
6264     // incoming edge to the PHI nodes, because both branch instructions target
6265     // now the same successor. Depending on the original branch condition
6266     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6267     // we perform the correct update for the PHI nodes.
6268     // This doesn't change the successor order of the just created branch
6269     // instruction (or any other instruction).
6270     if (Opc == Instruction::Or)
6271       std::swap(TBB, FBB);
6272
6273     // Replace the old BB with the new BB.
6274     for (auto &I : *TBB) {
6275       PHINode *PN = dyn_cast<PHINode>(&I);
6276       if (!PN)
6277         break;
6278       int i;
6279       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6280         PN->setIncomingBlock(i, TmpBB);
6281     }
6282
6283     // Add another incoming edge form the new BB.
6284     for (auto &I : *FBB) {
6285       PHINode *PN = dyn_cast<PHINode>(&I);
6286       if (!PN)
6287         break;
6288       auto *Val = PN->getIncomingValueForBlock(&BB);
6289       PN->addIncoming(Val, TmpBB);
6290     }
6291
6292     // Update the branch weights (from SelectionDAGBuilder::
6293     // FindMergedConditions).
6294     if (Opc == Instruction::Or) {
6295       // Codegen X | Y as:
6296       // BB1:
6297       //   jmp_if_X TBB
6298       //   jmp TmpBB
6299       // TmpBB:
6300       //   jmp_if_Y TBB
6301       //   jmp FBB
6302       //
6303
6304       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6305       // The requirement is that
6306       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6307       //     = TrueProb for orignal BB.
6308       // Assuming the orignal weights are A and B, one choice is to set BB1's
6309       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6310       // assumes that
6311       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6312       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6313       // TmpBB, but the math is more complicated.
6314       uint64_t TrueWeight, FalseWeight;
6315       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6316         uint64_t NewTrueWeight = TrueWeight;
6317         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6318         scaleWeights(NewTrueWeight, NewFalseWeight);
6319         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6320                          .createBranchWeights(TrueWeight, FalseWeight));
6321
6322         NewTrueWeight = TrueWeight;
6323         NewFalseWeight = 2 * FalseWeight;
6324         scaleWeights(NewTrueWeight, NewFalseWeight);
6325         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6326                          .createBranchWeights(TrueWeight, FalseWeight));
6327       }
6328     } else {
6329       // Codegen X & Y as:
6330       // BB1:
6331       //   jmp_if_X TmpBB
6332       //   jmp FBB
6333       // TmpBB:
6334       //   jmp_if_Y TBB
6335       //   jmp FBB
6336       //
6337       //  This requires creation of TmpBB after CurBB.
6338
6339       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6340       // The requirement is that
6341       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6342       //     = FalseProb for orignal BB.
6343       // Assuming the orignal weights are A and B, one choice is to set BB1's
6344       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6345       // assumes that
6346       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6347       uint64_t TrueWeight, FalseWeight;
6348       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6349         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6350         uint64_t NewFalseWeight = FalseWeight;
6351         scaleWeights(NewTrueWeight, NewFalseWeight);
6352         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6353                          .createBranchWeights(TrueWeight, FalseWeight));
6354
6355         NewTrueWeight = 2 * TrueWeight;
6356         NewFalseWeight = FalseWeight;
6357         scaleWeights(NewTrueWeight, NewFalseWeight);
6358         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6359                          .createBranchWeights(TrueWeight, FalseWeight));
6360       }
6361     }
6362
6363     // Note: No point in getting fancy here, since the DT info is never
6364     // available to CodeGenPrepare.
6365     ModifiedDT = true;
6366
6367     MadeChange = true;
6368
6369     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6370           TmpBB->dump());
6371   }
6372   return MadeChange;
6373 }