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