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