Fixes a bug in finding the upcoming store/conditional branch instruction
[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   public:
158     static char ID; // Pass identification, replacement for typeid
159     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
160         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
161         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
162       }
163     bool runOnFunction(Function &F) override;
164
165     const char *getPassName() const override { return "CodeGen Prepare"; }
166
167     void getAnalysisUsage(AnalysisUsage &AU) const override {
168       AU.addPreserved<DominatorTreeWrapperPass>();
169       AU.addRequired<TargetLibraryInfoWrapperPass>();
170       AU.addRequired<TargetTransformInfoWrapperPass>();
171     }
172
173   private:
174     bool eliminateFallThrough(Function &F);
175     bool eliminateMostlyEmptyBlocks(Function &F);
176     bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
177     void eliminateMostlyEmptyBlock(BasicBlock *BB);
178     bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
179     bool optimizeInst(Instruction *I, bool& ModifiedDT);
180     bool optimizeMemoryInst(Instruction *I, Value *Addr,
181                             Type *AccessTy, unsigned AS);
182     bool optimizeInlineAsmInst(CallInst *CS);
183     bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
184     bool moveExtToFormExtLoad(Instruction *&I);
185     bool optimizeExtUses(Instruction *I);
186     bool optimizeLoadExt(LoadInst *I);
187     bool optimizeSelectInst(SelectInst *SI);
188     bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
189     bool optimizeSwitchInst(SwitchInst *CI);
190     bool optimizeExtractElementInst(Instruction *Inst);
191     bool dupRetToEnableTailCallOpts(BasicBlock *BB);
192     bool placeDbgValues(Function &F);
193     bool sinkAndCmp(Function &F);
194     bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
195                         Instruction *&Inst,
196                         const SmallVectorImpl<Instruction *> &Exts,
197                         unsigned CreatedInstCost);
198     bool splitBranchCondition(Function &F);
199     bool simplifyOffsetableRelocate(Instruction &I);
200     void stripInvariantGroupMetadata(Instruction &I);
201   };
202 }
203
204 char CodeGenPrepare::ID = 0;
205 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
206                    "Optimize for code generation", false, false)
207
208 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
209   return new CodeGenPrepare(TM);
210 }
211
212 namespace {
213
214 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal);
215 Value* GetUntaintedAddress(Value* CurrentAddress);
216
217 // The depth we trace down a variable to look for its dependence set.
218 const unsigned kDependenceDepth = 4;
219
220 // Recursively looks for variables that 'Val' depends on at the given depth
221 // 'Depth', and adds them in 'DepSet'. If 'InsertOnlyLeafNodes' is true, only
222 // inserts the leaf node values; otherwise, all visited nodes are included in
223 // 'DepSet'. Note that constants will be ignored.
224 template <typename SetType>
225 void recursivelyFindDependence(SetType* DepSet, Value* Val,
226                                bool InsertOnlyLeafNodes = false,
227                                unsigned Depth = kDependenceDepth) {
228   if (Val == nullptr) {
229     return;
230   }
231   if (!InsertOnlyLeafNodes && !isa<Constant>(Val)) {
232     DepSet->insert(Val);
233   }
234   if (Depth == 0) {
235     // Cannot go deeper. Insert the leaf nodes.
236     if (InsertOnlyLeafNodes && !isa<Constant>(Val)) {
237       DepSet->insert(Val);
238     }
239     return;
240   }
241
242   // Go one step further to explore the dependence of the operands.
243   Instruction* I = nullptr;
244   if ((I = dyn_cast<Instruction>(Val))) {
245     if (isa<LoadInst>(I)) {
246       // A load is considerd the leaf load of the dependence tree. Done.
247       DepSet->insert(Val);
248       return;
249     } else if (I->isBinaryOp()) {
250       BinaryOperator* I = dyn_cast<BinaryOperator>(Val);
251       Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
252       recursivelyFindDependence(DepSet, Op0, Depth - 1);
253       recursivelyFindDependence(DepSet, Op1, Depth - 1);
254     } else if (I->isCast()) {
255       Value* Op0 = I->getOperand(0);
256       recursivelyFindDependence(DepSet, Op0, Depth - 1);
257     } else if (I->getOpcode() == Instruction::Select) {
258       Value* Op0 = I->getOperand(0);
259       Value* Op1 = I->getOperand(1);
260       Value* Op2 = I->getOperand(2);
261       recursivelyFindDependence(DepSet, Op0, Depth - 1);
262       recursivelyFindDependence(DepSet, Op1, Depth - 1);
263       recursivelyFindDependence(DepSet, Op2, Depth - 1);
264     } else if (I->getOpcode() == Instruction::GetElementPtr) {
265       for (unsigned i = 0; i < I->getNumOperands(); i++) {
266         recursivelyFindDependence(DepSet, I->getOperand(i), Depth - 1);
267       }
268     } else if (I->getOpcode() == Instruction::Store) {
269       auto* SI = dyn_cast<StoreInst>(Val);
270       recursivelyFindDependence(DepSet, SI->getPointerOperand(), Depth - 1);
271       recursivelyFindDependence(DepSet, SI->getValueOperand(), Depth - 1);
272     } else {
273       Value* Op0 = nullptr;
274       Value* Op1 = nullptr;
275       switch (I->getOpcode()) {
276         case Instruction::ICmp:
277         case Instruction::FCmp: {
278           Op0 = I->getOperand(0);
279           Op1 = I->getOperand(1);
280           recursivelyFindDependence(DepSet, Op0, Depth - 1);
281           recursivelyFindDependence(DepSet, Op1, Depth - 1);
282           break;
283         }
284         default: {
285           // Be conservative. Add it and be done with it.
286           DepSet->insert(Val);
287           return;
288         }
289       }
290     }
291   } else if (isa<Constant>(Val)) {
292     // Not interested in constant values. Done.
293     return;
294   } else {
295     // Be conservative. Add it and be done with it.
296     DepSet->insert(Val);
297     return;
298   }
299 }
300
301 // Helper function to create a Cast instruction.
302 Value* createCast(IRBuilder<true, NoFolder>& Builder, Value* DepVal,
303                   Type* TargetIntegerType) {
304   Instruction::CastOps CastOp = Instruction::BitCast;
305   switch (DepVal->getType()->getTypeID()) {
306     case Type::IntegerTyID: {
307       CastOp = Instruction::SExt;
308       break;
309     }
310     case Type::FloatTyID:
311     case Type::DoubleTyID: {
312       CastOp = Instruction::FPToSI;
313       break;
314     }
315     case Type::PointerTyID: {
316       CastOp = Instruction::PtrToInt;
317       break;
318     }
319     default: { break; }
320   }
321
322   return Builder.CreateCast(CastOp, DepVal, TargetIntegerType);
323 }
324
325 // Given a value, if it's a tainted address, this function returns the
326 // instruction that ORs the "dependence value" with the "original address".
327 // Otherwise, returns nullptr.  This instruction is the first OR instruction
328 // where one of its operand is an AND instruction with an operand being 0.
329 //
330 // E.g., it returns '%4 = or i32 %3, %2' given 'CurrentAddress' is '%5'.
331 // %0 = load i32, i32* @y, align 4, !tbaa !1
332 // %cmp = icmp ne i32 %0, 42  // <== this is like the condition
333 // %1 = sext i1 %cmp to i32
334 // %2 = ptrtoint i32* @x to i32
335 // %3 = and i32 %1, 0
336 // %4 = or i32 %3, %2
337 // %5 = inttoptr i32 %4 to i32*
338 // store i32 1, i32* %5, align 4
339 Instruction* getOrAddress(Value* CurrentAddress) {
340   // Is it a cast from integer to pointer type.
341   Instruction* OrAddress = nullptr;
342   Instruction* AndDep = nullptr;
343   Instruction* CastToInt = nullptr;
344   Value* ActualAddress = nullptr;
345   Constant* ZeroConst = nullptr;
346
347   const Instruction* CastToPtr = dyn_cast<Instruction>(CurrentAddress);
348   if (CastToPtr && CastToPtr->getOpcode() == Instruction::IntToPtr) {
349     // Is it an OR instruction: %1 = or %and, %actualAddress.
350     if ((OrAddress = dyn_cast<Instruction>(CastToPtr->getOperand(0))) &&
351         OrAddress->getOpcode() == Instruction::Or) {
352       // The first operand should be and AND instruction.
353       AndDep = dyn_cast<Instruction>(OrAddress->getOperand(0));
354       if (AndDep && AndDep->getOpcode() == Instruction::And) {
355         // Also make sure its first operand of the "AND" is 0, or the "AND" is
356         // marked explicitly by "NoInstCombine".
357         if ((ZeroConst = dyn_cast<Constant>(AndDep->getOperand(1))) &&
358             ZeroConst->isNullValue()) {
359           return OrAddress;
360         }
361       }
362     }
363   }
364   // Looks like it's not been tainted.
365   return nullptr;
366 }
367
368 // Given a value, if it's a tainted address, this function returns the
369 // instruction that taints the "dependence value". Otherwise, returns nullptr.
370 // This instruction is the last AND instruction where one of its operand is 0.
371 // E.g., it returns '%3' given 'CurrentAddress' is '%5'.
372 // %0 = load i32, i32* @y, align 4, !tbaa !1
373 // %cmp = icmp ne i32 %0, 42  // <== this is like the condition
374 // %1 = sext i1 %cmp to i32
375 // %2 = ptrtoint i32* @x to i32
376 // %3 = and i32 %1, 0
377 // %4 = or i32 %3, %2
378 // %5 = inttoptr i32 %4 to i32*
379 // store i32 1, i32* %5, align 4
380 Instruction* getAndDependence(Value* CurrentAddress) {
381   // If 'CurrentAddress' is tainted, get the OR instruction.
382   auto* OrAddress = getOrAddress(CurrentAddress);
383   if (OrAddress == nullptr) {
384     return nullptr;
385   }
386
387   // No need to check the operands.
388   auto* AndDepInst = dyn_cast<Instruction>(OrAddress->getOperand(0));
389   assert(AndDepInst);
390   return AndDepInst;
391 }
392
393 // Given a value, if it's a tainted address, this function returns
394 // the "dependence value", which is the first operand in the AND instruction.
395 // E.g., it returns '%1' given 'CurrentAddress' is '%5'.
396 // %0 = load i32, i32* @y, align 4, !tbaa !1
397 // %cmp = icmp ne i32 %0, 42  // <== this is like the condition
398 // %1 = sext i1 %cmp to i32
399 // %2 = ptrtoint i32* @x to i32
400 // %3 = and i32 %1, 0
401 // %4 = or i32 %3, %2
402 // %5 = inttoptr i32 %4 to i32*
403 // store i32 1, i32* %5, align 4
404 Value* getDependence(Value* CurrentAddress) {
405   auto* AndInst = getAndDependence(CurrentAddress);
406   if (AndInst == nullptr) {
407     return nullptr;
408   }
409   return AndInst->getOperand(0);
410 }
411
412 // Given an address that has been tainted, returns the only condition it depends
413 // on, if any; otherwise, returns nullptr.
414 Value* getConditionDependence(Value* Address) {
415   auto* Dep = getDependence(Address);
416   if (Dep == nullptr) {
417     // 'Address' has not been dependence-tainted.
418     return nullptr;
419   }
420
421   Value* Operand = Dep;
422   while (true) {
423     auto* Inst = dyn_cast<Instruction>(Operand);
424     if (Inst == nullptr) {
425       // Non-instruction type does not have condition dependence.
426       return nullptr;
427     }
428     if (Inst->getOpcode() == Instruction::ICmp) {
429       return Inst;
430     } else {
431       if (Inst->getNumOperands() != 1) {
432         return nullptr;
433       } else {
434         Operand = Inst->getOperand(0);
435       }
436     }
437   }
438 }
439
440 // Conservatively decides whether the dependence set of 'Val1' includes the
441 // dependence set of 'Val2'. If 'ExpandSecondValue' is false, we do not expand
442 // 'Val2' and use that single value as its dependence set.
443 // If it returns true, it means the dependence set of 'Val1' includes that of
444 // 'Val2'; otherwise, it only means we cannot conclusively decide it.
445 bool dependenceSetInclusion(Value* Val1, Value* Val2,
446                             int Val1ExpandLevel = 2 * kDependenceDepth,
447                             int Val2ExpandLevel = kDependenceDepth) {
448   typedef SmallSet<Value*, 8> IncludingSet;
449   typedef SmallSet<Value*, 4> IncludedSet;
450
451   IncludingSet DepSet1;
452   IncludedSet DepSet2;
453   // Look for more depths for the including set.
454   recursivelyFindDependence(&DepSet1, Val1, false /*Insert all visited nodes*/,
455                             Val1ExpandLevel);
456   recursivelyFindDependence(&DepSet2, Val2, true /*Only insert leaf nodes*/,
457                             Val2ExpandLevel);
458
459   auto set_inclusion = [](IncludingSet FullSet, IncludedSet Subset) {
460     for (auto* Dep : Subset) {
461       if (0 == FullSet.count(Dep)) {
462         return false;
463       }
464     }
465     return true;
466   };
467   bool inclusion = set_inclusion(DepSet1, DepSet2);
468   DEBUG(dbgs() << "[dependenceSetInclusion]: " << inclusion << "\n");
469   DEBUG(dbgs() << "Including set for: " << *Val1 << "\n");
470   DEBUG(for (const auto* Dep : DepSet1) { dbgs() << "\t\t" << *Dep << "\n"; });
471   DEBUG(dbgs() << "Included set for: " << *Val2 << "\n");
472   DEBUG(for (const auto* Dep : DepSet2) { dbgs() << "\t\t" << *Dep << "\n"; });
473
474   return inclusion;
475 }
476
477 // Recursively iterates through the operands spawned from 'DepVal'. If there
478 // exists a single value that 'DepVal' only depends on, we call that value the
479 // root dependence of 'DepVal' and return it. Otherwise, return 'DepVal'.
480 Value* getRootDependence(Value* DepVal) {
481   SmallSet<Value*, 8> DepSet;
482   for (unsigned depth = kDependenceDepth; depth > 0; --depth) {
483     recursivelyFindDependence(&DepSet, DepVal, true /*Only insert leaf nodes*/,
484                               depth);
485     if (DepSet.size() == 1) {
486       return *DepSet.begin();
487     }
488     DepSet.clear();
489   }
490   return DepVal;
491 }
492
493 // This function actually taints 'DepVal' to the address to 'SI'. If the
494 // address
495 // of 'SI' already depends on whatever 'DepVal' depends on, this function
496 // doesn't do anything and returns false. Otherwise, returns true.
497 //
498 // This effect forces the store and any stores that comes later to depend on
499 // 'DepVal'. For example, we have a condition "cond", and a store instruction
500 // "s: STORE addr, val". If we want "s" (and any later store) to depend on
501 // "cond", we do the following:
502 // %conv = sext i1 %cond to i32
503 // %addrVal = ptrtoint i32* %addr to i32
504 // %andCond = and i32 conv, 0;
505 // %orAddr = or i32 %andCond, %addrVal;
506 // %NewAddr = inttoptr i32 %orAddr to i32*;
507 //
508 // This is a more concrete example:
509 // ------
510 // %0 = load i32, i32* @y, align 4, !tbaa !1
511 // %cmp = icmp ne i32 %0, 42  // <== this is like the condition
512 // %1 = sext i1 %cmp to i32
513 // %2 = ptrtoint i32* @x to i32
514 // %3 = and i32 %1, 0
515 // %4 = or i32 %3, %2
516 // %5 = inttoptr i32 %4 to i32*
517 // store i32 1, i32* %5, align 4
518 bool taintStoreAddress(StoreInst* SI, Value* DepVal,
519                        const char* calling_func = __builtin_FUNCTION()) {
520   DEBUG(dbgs() << "Called from " << calling_func << '\n');
521   // Set the insertion point right after the 'DepVal'.
522   Instruction* Inst = nullptr;
523   IRBuilder<true, NoFolder> Builder(SI);
524   BasicBlock* BB = SI->getParent();
525   Value* Address = SI->getPointerOperand();
526   Type* TargetIntegerType =
527       IntegerType::get(Address->getContext(),
528                        BB->getModule()->getDataLayout().getPointerSizeInBits());
529
530   // Does SI's address already depends on whatever 'DepVal' depends on?
531   if (StoreAddressDependOnValue(SI, DepVal)) {
532     return false;
533   }
534
535   // Figure out if there's a root variable 'DepVal' depends on. For example, we
536   // can extract "getelementptr inbounds %struct, %struct* %0, i64 0, i32 123"
537   // to be "%struct* %0" since all other operands are constant.
538   DepVal = getRootDependence(DepVal);
539
540   // Is this already a dependence-tainted store?
541   Value* OldDep = getDependence(Address);
542   if (OldDep) {
543     // The address of 'SI' has already been tainted.  Just need to absorb the
544     // DepVal to the existing dependence in the address of SI.
545     Instruction* AndDep = getAndDependence(Address);
546     IRBuilder<true, NoFolder> Builder(AndDep);
547     Value* NewDep = nullptr;
548     if (DepVal->getType() == AndDep->getType()) {
549       NewDep = Builder.CreateAnd(OldDep, DepVal);
550     } else {
551       NewDep = Builder.CreateAnd(
552           OldDep, createCast(Builder, DepVal, TargetIntegerType));
553     }
554
555     auto* NewDepInst = dyn_cast<Instruction>(NewDep);
556
557     // Use the new AND instruction as the dependence
558     AndDep->setOperand(0, NewDep);
559     return true;
560   }
561
562   // SI's address has not been tainted. Now taint it with 'DepVal'.
563   Value* CastDepToInt = createCast(Builder, DepVal, TargetIntegerType);
564   Value* PtrToIntCast = Builder.CreatePtrToInt(Address, TargetIntegerType);
565   Value* AndDepVal =
566       Builder.CreateAnd(CastDepToInt, ConstantInt::get(TargetIntegerType, 0));
567   auto AndInst = dyn_cast<Instruction>(AndDepVal);
568   // XXX-comment: The original IR InstCombiner would change our and instruction
569   // to a select and then the back end optimize the condition out.  We attach a
570   // flag to instructions and set it here to inform the InstCombiner to not to
571   // touch this and instruction at all.
572   Value* OrAddr = Builder.CreateOr(AndDepVal, PtrToIntCast);
573   Value* NewAddr = Builder.CreateIntToPtr(OrAddr, Address->getType());
574
575   DEBUG(dbgs() << "[taintStoreAddress]\n"
576                << "Original store: " << *SI << '\n');
577   SI->setOperand(1, NewAddr);
578
579   // Debug output.
580   DEBUG(dbgs() << "\tTargetIntegerType: " << *TargetIntegerType << '\n'
581                << "\tCast dependence value to integer: " << *CastDepToInt
582                << '\n'
583                << "\tCast address to integer: " << *PtrToIntCast << '\n'
584                << "\tAnd dependence value: " << *AndDepVal << '\n'
585                << "\tOr address: " << *OrAddr << '\n'
586                << "\tCast or instruction to address: " << *NewAddr << "\n\n");
587
588   return true;
589 }
590
591 // Looks for the previous store in the if block --- 'BrBB', which makes the
592 // speculative store 'StoreToHoist' safe.
593 Value* getSpeculativeStoreInPrevBB(StoreInst* StoreToHoist, BasicBlock* BrBB) {
594   assert(StoreToHoist && "StoreToHoist must be a real store");
595
596   Value* StorePtr = StoreToHoist->getPointerOperand();
597
598   // Look for a store to the same pointer in BrBB.
599   for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), RE = BrBB->rend();
600        RI != RE; ++RI) {
601     Instruction* CurI = &*RI;
602
603     StoreInst* SI = dyn_cast<StoreInst>(CurI);
604     // Found the previous store make sure it stores to the same location.
605     // XXX-update: If the previous store's original untainted address are the
606     // same as 'StorePtr', we are also good to hoist the store.
607     if (SI && (SI->getPointerOperand() == StorePtr ||
608                GetUntaintedAddress(SI->getPointerOperand()) == StorePtr)) {
609       // Found the previous store, return its value operand.
610       return SI;
611     }
612   }
613
614   assert(false &&
615          "We should not reach here since this store is safe to speculate");
616 }
617
618 // XXX-comment: Returns true if it changes the code, false otherwise (the branch
619 // condition already depends on 'DepVal'.
620 bool taintConditionalBranch(BranchInst* BI, Value* DepVal) {
621   assert(BI->isConditional());
622   auto* Cond = BI->getOperand(0);
623   if (dependenceSetInclusion(Cond, DepVal)) {
624     // The dependence/ordering is self-evident.
625     return false;
626   }
627
628   IRBuilder<true, NoFolder> Builder(BI);
629   auto* AndDep =
630       Builder.CreateAnd(DepVal, ConstantInt::get(DepVal->getType(), 0));
631   auto* TruncAndDep =
632       Builder.CreateTrunc(AndDep, IntegerType::get(DepVal->getContext(), 1));
633   auto* OrCond = Builder.CreateOr(TruncAndDep, Cond);
634   BI->setOperand(0, OrCond);
635
636   // Debug output.
637   DEBUG(dbgs() << "\tTainted branch condition:\n" << *BI->getParent());
638
639   return true;
640 }
641
642 bool ConditionalBranchDependsOnValue(BranchInst* BI, Value* DepVal) {
643   assert(BI->isConditional());
644   auto* Cond = BI->getOperand(0);
645   return dependenceSetInclusion(Cond, DepVal);
646 }
647
648 // XXX-update: For a relaxed load 'LI', find the first immediate atomic store or
649 // the first conditional branch. Returns nullptr if there's no such immediately
650 // following store/branch instructions, which we can only enforce the load with
651 // 'acquire'.
652 Instruction* findFirstStoreCondBranchInst(LoadInst* LI) {
653   // In some situations, relaxed loads can be left as is:
654   // 1. The relaxed load is used to calculate the address of the immediate
655   // following store;
656   // 2. The relaxed load is used as a condition in the immediate following
657   // condition, and there are no stores in between. This is actually quite
658   // common. E.g.,
659   // int r1 = x.load(relaxed);
660   // if (r1 != 0) {
661   //   y.store(1, relaxed);
662   // }
663   // However, in this function, we don't deal with them directly. Instead, we
664   // just find the immediate following store/condition branch and return it.
665
666   auto* BB = LI->getParent();
667   auto BE = BB->end();
668   auto BBI = BasicBlock::iterator(LI);
669   BBI++;
670   for (; BBI != BE; BBI++) {
671     auto* Inst = dyn_cast<Instruction>(&*BBI);
672     if (Inst == nullptr) {
673       continue;
674     }
675     if (Inst->getOpcode() == Instruction::Store) {
676       return Inst;
677     } else if (Inst->getOpcode() == Instruction::Br) {
678       auto* BrInst = dyn_cast<BranchInst>(Inst);
679       if (BrInst->isConditional()) {
680         return Inst;
681       } else {
682         return nullptr;
683       }
684     }
685   }
686   return nullptr;
687 }
688
689 // XXX-comment: Returns whether the code has been changed.
690 bool taintMonotonicLoads(const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
691   bool Changed = false;
692   for (auto* LI : MonotonicLoadInsts) {
693     auto* FirstInst = findFirstStoreCondBranchInst(LI);
694     if (FirstInst == nullptr) {
695       // We don't seem to be able to taint a following store/conditional branch
696       // instruction. Simply make it acquire.
697       DEBUG(dbgs() << "[RelaxedLoad]: Transformed to acquire load\n"
698                    << *LI << "\n");
699       LI->setOrdering(Acquire);
700       Changed = true;
701       continue;
702     }
703     // Taint 'FirstInst', which could be a store or a condition branch
704     // instruction.
705     if (FirstInst->getOpcode() == Instruction::Store) {
706       Changed |= taintStoreAddress(dyn_cast<StoreInst>(FirstInst), LI);
707     } else if (FirstInst->getOpcode() == Instruction::Br) {
708       Changed |= taintConditionalBranch(dyn_cast<BranchInst>(FirstInst), LI);
709     } else {
710       assert(false && "findFirstStoreCondBranchInst() should return a "
711                     "store/condition branch instruction");
712     }
713   }
714   return Changed;
715 }
716
717 // Inserts a fake conditional branch right after the instruction 'SplitInst',
718 // and the branch condition is 'Condition'. 'SplitInst' will be placed in the
719 // newly created block.
720 void AddFakeConditionalBranch(Instruction* SplitInst, Value* Condition) {
721   auto* BB = SplitInst->getParent();
722   TerminatorInst* ThenTerm = nullptr;
723   TerminatorInst* ElseTerm = nullptr;
724   SplitBlockAndInsertIfThenElse(Condition, SplitInst, &ThenTerm, &ElseTerm);
725   assert(ThenTerm && ElseTerm &&
726          "Then/Else terminators cannot be empty after basic block spliting");
727   auto* ThenBB = ThenTerm->getParent();
728   auto* ElseBB = ElseTerm->getParent();
729   auto* TailBB = ThenBB->getSingleSuccessor();
730   assert(TailBB && "Tail block cannot be empty after basic block spliting");
731
732   ThenBB->disableCanEliminateBlock();
733   ThenBB->disableCanEliminateBlock();
734   TailBB->disableCanEliminateBlock();
735   ThenBB->setName(BB->getName() + "Then.Fake");
736   ElseBB->setName(BB->getName() + "Else.Fake");
737   DEBUG(dbgs() << "Add fake conditional branch:\n"
738                << "Then Block:\n"
739                << *ThenBB << "Else Block:\n"
740                << *ElseBB << "\n");
741 }
742
743 // Returns true if the code is changed, and false otherwise.
744 void TaintRelaxedLoads(LoadInst* LI) {
745   // For better performance, we can add a "AND X 0" instruction before the
746   // condition.
747   auto* FirstInst = findFirstStoreCondBranchInst(LI);
748   Instruction* InsertPoint = nullptr;
749   if (FirstInst == nullptr) {
750     InsertPoint = LI->getParent()->getTerminator();
751     InsertPoint = LI->getNextNode();
752   } else {
753     InsertPoint = LI->getNextNode();
754   }
755   IRBuilder<true, NoFolder> Builder(InsertPoint);
756   auto* AndZero = dyn_cast<Instruction>(
757       Builder.CreateAnd(LI, Constant::getNullValue(LI->getType())));
758   auto* FakeCondition = dyn_cast<Instruction>(Builder.CreateICmp(
759       CmpInst::ICMP_NE, AndZero, Constant::getNullValue(LI->getType())));
760   AddFakeConditionalBranch(FakeCondition->getNextNode(), FakeCondition);
761 }
762
763 // XXX-comment: Returns whether the code has been changed.
764 bool AddFakeConditionalBranchAfterMonotonicLoads(
765     const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
766   bool Changed = false;
767   for (auto* LI : MonotonicLoadInsts) {
768     auto* FirstInst = findFirstStoreCondBranchInst(LI);
769     if (FirstInst != nullptr) {
770       if (FirstInst->getOpcode() == Instruction::Store) {
771         if (StoreAddressDependOnValue(dyn_cast<StoreInst>(FirstInst), LI)) {
772           continue;
773         }
774       } else if (FirstInst->getOpcode() == Instruction::Br &&
775                  isa<BranchInst>(FirstInst)) {
776         if (ConditionalBranchDependsOnValue(dyn_cast<BranchInst>(FirstInst),
777                                             LI)) {
778           continue;
779         }
780       } else {
781         dbgs() << "FirstInst=" << *FirstInst << "\n";
782         assert(false && "findFirstStoreCondBranchInst() should return a "
783                         "store/condition branch instruction");
784       }
785     }
786
787     // We really need to process the relaxed load now.
788     StoreInst* SI = nullptr;;
789     if (FirstInst && (SI = dyn_cast<StoreInst>(FirstInst))) {
790       // For immediately coming stores, taint the address of the store.
791       taintStoreAddress(SI, LI);
792     } else {
793       // For immediately coming branch, directly add a fake branch.
794       TaintRelaxedLoads(LI);
795       Changed = true;
796     }
797   }
798   return Changed;
799 }
800
801 /**** Implementations of public methods for dependence tainting ****/
802 Value* GetUntaintedAddress(Value* CurrentAddress) {
803   auto* OrAddress = getOrAddress(CurrentAddress);
804   if (OrAddress == nullptr) {
805     // Is it tainted by a select instruction?
806     auto* Inst = dyn_cast<Instruction>(CurrentAddress);
807     if (nullptr != Inst && Inst->getOpcode() == Instruction::Select) {
808       // A selection instruction.
809       if (Inst->getOperand(1) == Inst->getOperand(2)) {
810         return Inst->getOperand(1);
811       }
812     }
813
814     return CurrentAddress;
815   }
816   Value* ActualAddress = nullptr;
817
818   auto* CastToInt = dyn_cast<Instruction>(OrAddress->getOperand(1));
819   if (CastToInt && CastToInt->getOpcode() == Instruction::PtrToInt) {
820     return CastToInt->getOperand(0);
821   } else {
822     // This should be a IntToPtr constant expression.
823     ConstantExpr* PtrToIntExpr =
824         dyn_cast<ConstantExpr>(OrAddress->getOperand(1));
825     if (PtrToIntExpr && PtrToIntExpr->getOpcode() == Instruction::PtrToInt) {
826       return PtrToIntExpr->getOperand(0);
827     }
828   }
829
830   // Looks like it's not been dependence-tainted. Returns itself.
831   return CurrentAddress;
832 }
833
834 MemoryLocation GetUntaintedMemoryLocation(StoreInst* SI) {
835   AAMDNodes AATags;
836   SI->getAAMetadata(AATags);
837   const auto& DL = SI->getModule()->getDataLayout();
838   const auto* OriginalAddr = GetUntaintedAddress(SI->getPointerOperand());
839   DEBUG(if (OriginalAddr != SI->getPointerOperand()) {
840     dbgs() << "[GetUntaintedMemoryLocation]\n"
841            << "Storing address: " << *SI->getPointerOperand()
842            << "\nUntainted address: " << *OriginalAddr << "\n";
843   });
844   return MemoryLocation(OriginalAddr,
845                         DL.getTypeStoreSize(SI->getValueOperand()->getType()),
846                         AATags);
847 }
848
849 bool TaintDependenceToStore(StoreInst* SI, Value* DepVal) {
850   if (dependenceSetInclusion(SI, DepVal)) {
851     return false;
852   }
853
854   bool tainted = taintStoreAddress(SI, DepVal);
855   assert(tainted);
856   return tainted;
857 }
858
859 bool TaintDependenceToStoreAddress(StoreInst* SI, Value* DepVal) {
860   if (dependenceSetInclusion(SI->getPointerOperand(), DepVal)) {
861     return false;
862   }
863
864   bool tainted = taintStoreAddress(SI, DepVal);
865   assert(tainted);
866   return tainted;
867 }
868
869 bool CompressTaintedStore(BasicBlock* BB) {
870   // This function looks for windows of adajcent stores in 'BB' that satisfy the
871   // following condition (and then do optimization):
872   // *Addr(d1) = v1, d1 is a condition and is the only dependence the store's
873   //                 address depends on && Dep(v1) includes Dep(d1);
874   // *Addr(d2) = v2, d2 is a condition and is the only dependnece the store's
875   //                 address depends on && Dep(v2) includes Dep(d2) &&
876   //                 Dep(d2) includes Dep(d1);
877   // ...
878   // *Addr(dN) = vN, dN is a condition and is the only dependence the store's
879   //                 address depends on && Dep(dN) includes Dep(d"N-1").
880   //
881   // As a result, Dep(dN) includes [Dep(d1) V ... V Dep(d"N-1")], so we can
882   // safely transform the above to the following. In between these stores, we
883   // can omit untainted stores to the same address 'Addr' since they internally
884   // have dependence on the previous stores on the same address.
885   // =>
886   // *Addr = v1
887   // *Addr = v2
888   // *Addr(d3) = v3
889   for (auto BI = BB->begin(), BE = BB->end(); BI != BE; BI++) {
890     // Look for the first store in such a window of adajacent stores.
891     auto* FirstSI = dyn_cast<StoreInst>(&*BI);
892     if (!FirstSI) {
893       continue;
894     }
895
896     // The first store in the window must be tainted.
897     auto* UntaintedAddress = GetUntaintedAddress(FirstSI->getPointerOperand());
898     if (UntaintedAddress == FirstSI->getPointerOperand()) {
899       continue;
900     }
901
902     // The first store's address must directly depend on and only depend on a
903     // condition.
904     auto* FirstSIDepCond = getConditionDependence(FirstSI->getPointerOperand());
905     if (nullptr == FirstSIDepCond) {
906       continue;
907     }
908
909     // Dep(first store's storing value) includes Dep(tainted dependence).
910     if (!dependenceSetInclusion(FirstSI->getValueOperand(), FirstSIDepCond)) {
911       continue;
912     }
913
914     // Look for subsequent stores to the same address that satisfy the condition
915     // of "compressing the dependence".
916     SmallVector<StoreInst*, 8> AdajacentStores;
917     AdajacentStores.push_back(FirstSI);
918     auto BII = BasicBlock::iterator(FirstSI);
919     for (BII++; BII != BE; BII++) {
920       auto* CurrSI = dyn_cast<StoreInst>(&*BII);
921       if (!CurrSI) {
922         if (BII->mayHaveSideEffects()) {
923           // Be conservative. Instructions with side effects are similar to
924           // stores.
925           break;
926         }
927         continue;
928       }
929
930       auto* OrigAddress = GetUntaintedAddress(CurrSI->getPointerOperand());
931       auto* CurrSIDepCond = getConditionDependence(CurrSI->getPointerOperand());
932       // All other stores must satisfy either:
933       // A. 'CurrSI' is an untainted store to the same address, or
934       // B. the combination of the following 5 subconditions:
935       // 1. Tainted;
936       // 2. Untainted address is the same as the group's address;
937       // 3. The address is tainted with a sole value which is a condition;
938       // 4. The storing value depends on the condition in 3.
939       // 5. The condition in 3 depends on the previous stores dependence
940       // condition.
941
942       // Condition A. Should ignore this store directly.
943       if (OrigAddress == CurrSI->getPointerOperand() &&
944           OrigAddress == UntaintedAddress) {
945         continue;
946       }
947       // Check condition B.
948       Value* Cond = nullptr;
949       if (OrigAddress == CurrSI->getPointerOperand() ||
950           OrigAddress != UntaintedAddress || CurrSIDepCond == nullptr ||
951           !dependenceSetInclusion(CurrSI->getValueOperand(), CurrSIDepCond)) {
952         // Check condition 1, 2, 3 & 4.
953         break;
954       }
955
956       // Check condition 5.
957       StoreInst* PrevSI = AdajacentStores[AdajacentStores.size() - 1];
958       auto* PrevSIDepCond = getConditionDependence(PrevSI->getPointerOperand());
959       assert(PrevSIDepCond &&
960              "Store in the group must already depend on a condtion");
961       if (!dependenceSetInclusion(CurrSIDepCond, PrevSIDepCond)) {
962         break;
963       }
964
965       AdajacentStores.push_back(CurrSI);
966     }
967
968     if (AdajacentStores.size() == 1) {
969       // The outer loop should keep looking from the next store.
970       continue;
971     }
972
973     // Now we have such a group of tainted stores to the same address.
974     DEBUG(dbgs() << "[CompressTaintedStore]\n");
975     DEBUG(dbgs() << "Original BB\n");
976     DEBUG(dbgs() << *BB << '\n');
977     auto* LastSI = AdajacentStores[AdajacentStores.size() - 1];
978     for (unsigned i = 0; i < AdajacentStores.size() - 1; ++i) {
979       auto* SI = AdajacentStores[i];
980
981       // Use the original address for stores before the last one.
982       SI->setOperand(1, UntaintedAddress);
983
984       DEBUG(dbgs() << "Store address has been reversed: " << *SI << '\n';);
985     }
986     // XXX-comment: Try to make the last store use fewer registers.
987     // If LastSI's storing value is a select based on the condition with which
988     // its address is tainted, transform the tainted address to a select
989     // instruction, as follows:
990     // r1 = Select Cond ? A : B
991     // r2 = Cond & 0
992     // r3 = Addr | r2
993     // *r3 = r1
994     // ==>
995     // r1 = Select Cond ? A : B
996     // r2 = Select Cond ? Addr : Addr
997     // *r2 = r1
998     // The idea is that both Select instructions depend on the same condition,
999     // so hopefully the backend can generate two cmov instructions for them (and
1000     // this saves the number of registers needed).
1001     auto* LastSIDep = getConditionDependence(LastSI->getPointerOperand());
1002     auto* LastSIValue = dyn_cast<Instruction>(LastSI->getValueOperand());
1003     if (LastSIValue && LastSIValue->getOpcode() == Instruction::Select &&
1004         LastSIValue->getOperand(0) == LastSIDep) {
1005       // XXX-comment: Maybe it's better for us to just leave it as an and/or
1006       // dependence pattern.
1007       //      /*
1008       IRBuilder<true, NoFolder> Builder(LastSI);
1009       auto* Address =
1010           Builder.CreateSelect(LastSIDep, UntaintedAddress, UntaintedAddress);
1011       LastSI->setOperand(1, Address);
1012       DEBUG(dbgs() << "The last store becomes :" << *LastSI << "\n\n";);
1013       //      */
1014     }
1015   }
1016
1017   return true;
1018 }
1019
1020 bool PassDependenceToStore(Value* OldAddress, StoreInst* NewStore) {
1021   Value* OldDep = getDependence(OldAddress);
1022   // Return false when there's no dependence to pass from the OldAddress.
1023   if (!OldDep) {
1024     return false;
1025   }
1026
1027   // No need to pass the dependence to NewStore's address if it already depends
1028   // on whatever 'OldAddress' depends on.
1029   if (StoreAddressDependOnValue(NewStore, OldDep)) {
1030     return false;
1031   }
1032   return taintStoreAddress(NewStore, OldAddress);
1033 }
1034
1035 SmallSet<Value*, 8> FindDependence(Value* Val) {
1036   SmallSet<Value*, 8> DepSet;
1037   recursivelyFindDependence(&DepSet, Val, true /*Only insert leaf nodes*/);
1038   return DepSet;
1039 }
1040
1041 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal) {
1042   return dependenceSetInclusion(SI->getPointerOperand(), DepVal);
1043 }
1044
1045 bool StoreDependOnValue(StoreInst* SI, Value* Dep) {
1046   return dependenceSetInclusion(SI, Dep);
1047 }
1048
1049 } // namespace
1050
1051
1052
1053 bool CodeGenPrepare::runOnFunction(Function &F) {
1054   bool EverMadeChange = false;
1055
1056   if (skipOptnoneFunction(F))
1057     return false;
1058
1059   DL = &F.getParent()->getDataLayout();
1060
1061   // Clear per function information.
1062   InsertedInsts.clear();
1063   PromotedInsts.clear();
1064
1065   ModifiedDT = false;
1066   if (TM)
1067     TLI = TM->getSubtargetImpl(F)->getTargetLowering();
1068   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1069   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1070   OptSize = F.optForSize();
1071
1072   /// This optimization identifies DIV instructions that can be
1073   /// profitably bypassed and carried out with a shorter, faster divide.
1074   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
1075     const DenseMap<unsigned int, unsigned int> &BypassWidths =
1076        TLI->getBypassSlowDivWidths();
1077     BasicBlock* BB = &*F.begin();
1078     while (BB != nullptr) {
1079       // bypassSlowDivision may create new BBs, but we don't want to reapply the
1080       // optimization to those blocks.
1081       BasicBlock* Next = BB->getNextNode();
1082       EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
1083       BB = Next;
1084     }
1085   }
1086
1087   // Eliminate blocks that contain only PHI nodes and an
1088   // unconditional branch.
1089   EverMadeChange |= eliminateMostlyEmptyBlocks(F);
1090
1091   // llvm.dbg.value is far away from the value then iSel may not be able
1092   // handle it properly. iSel will drop llvm.dbg.value if it can not
1093   // find a node corresponding to the value.
1094   EverMadeChange |= placeDbgValues(F);
1095
1096   // If there is a mask, compare against zero, and branch that can be combined
1097   // into a single target instruction, push the mask and compare into branch
1098   // users. Do this before OptimizeBlock -> OptimizeInst ->
1099   // OptimizeCmpExpression, which perturbs the pattern being searched for.
1100   if (!DisableBranchOpts) {
1101     EverMadeChange |= sinkAndCmp(F);
1102     EverMadeChange |= splitBranchCondition(F);
1103   }
1104
1105   bool MadeChange = true;
1106   while (MadeChange) {
1107     MadeChange = false;
1108     for (Function::iterator I = F.begin(); I != F.end(); ) {
1109       BasicBlock *BB = &*I++;
1110       bool ModifiedDTOnIteration = false;
1111       MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
1112
1113       // Restart BB iteration if the dominator tree of the Function was changed
1114       if (ModifiedDTOnIteration)
1115         break;
1116     }
1117     EverMadeChange |= MadeChange;
1118   }
1119
1120   SunkAddrs.clear();
1121
1122   if (!DisableBranchOpts) {
1123     MadeChange = false;
1124     SmallPtrSet<BasicBlock*, 8> WorkList;
1125     for (BasicBlock &BB : F) {
1126       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
1127       MadeChange |= ConstantFoldTerminator(&BB, true);
1128       if (!MadeChange) continue;
1129
1130       for (SmallVectorImpl<BasicBlock*>::iterator
1131              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1132         if (pred_begin(*II) == pred_end(*II))
1133           WorkList.insert(*II);
1134     }
1135
1136     // Delete the dead blocks and any of their dead successors.
1137     MadeChange |= !WorkList.empty();
1138     while (!WorkList.empty()) {
1139       BasicBlock *BB = *WorkList.begin();
1140       WorkList.erase(BB);
1141       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
1142
1143       DeleteDeadBlock(BB);
1144
1145       for (SmallVectorImpl<BasicBlock*>::iterator
1146              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1147         if (pred_begin(*II) == pred_end(*II))
1148           WorkList.insert(*II);
1149     }
1150
1151     // Merge pairs of basic blocks with unconditional branches, connected by
1152     // a single edge.
1153     if (EverMadeChange || MadeChange)
1154       MadeChange |= eliminateFallThrough(F);
1155
1156     EverMadeChange |= MadeChange;
1157   }
1158
1159   if (!DisableGCOpts) {
1160     SmallVector<Instruction *, 2> Statepoints;
1161     for (BasicBlock &BB : F)
1162       for (Instruction &I : BB)
1163         if (isStatepoint(I))
1164           Statepoints.push_back(&I);
1165     for (auto &I : Statepoints)
1166       EverMadeChange |= simplifyOffsetableRelocate(*I);
1167   }
1168
1169   // XXX-comment: Delay dealing with relaxed loads in this function to avoid
1170   // further changes done by other passes (e.g., SimplifyCFG).
1171   // Collect all the relaxed loads.
1172   SmallVector<LoadInst*, 1> MonotonicLoadInsts;
1173   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
1174     if (I->isAtomic()) {
1175       switch (I->getOpcode()) {
1176         case Instruction::Load: {
1177           auto* LI = dyn_cast<LoadInst>(&*I);
1178           if (LI->getOrdering() == Monotonic) {
1179             MonotonicLoadInsts.push_back(LI);
1180           }
1181           break;
1182         }
1183         default: {
1184           break;
1185         }
1186       }
1187     }
1188   }
1189   EverMadeChange |=
1190       AddFakeConditionalBranchAfterMonotonicLoads(MonotonicLoadInsts);
1191
1192   return EverMadeChange;
1193 }
1194
1195 /// Merge basic blocks which are connected by a single edge, where one of the
1196 /// basic blocks has a single successor pointing to the other basic block,
1197 /// which has a single predecessor.
1198 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
1199   bool Changed = false;
1200   // Scan all of the blocks in the function, except for the entry block.
1201   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1202     BasicBlock *BB = &*I++;
1203     // If the destination block has a single pred, then this is a trivial
1204     // edge, just collapse it.
1205     BasicBlock *SinglePred = BB->getSinglePredecessor();
1206
1207     // Don't merge if BB's address is taken.
1208     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
1209
1210     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
1211     if (Term && !Term->isConditional()) {
1212       Changed = true;
1213       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
1214       // Remember if SinglePred was the entry block of the function.
1215       // If so, we will need to move BB back to the entry position.
1216       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1217       MergeBasicBlockIntoOnlyPred(BB, nullptr);
1218
1219       if (isEntry && BB != &BB->getParent()->getEntryBlock())
1220         BB->moveBefore(&BB->getParent()->getEntryBlock());
1221
1222       // We have erased a block. Update the iterator.
1223       I = BB->getIterator();
1224     }
1225   }
1226   return Changed;
1227 }
1228
1229 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
1230 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
1231 /// edges in ways that are non-optimal for isel. Start by eliminating these
1232 /// blocks so we can split them the way we want them.
1233 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
1234   bool MadeChange = false;
1235   // Note that this intentionally skips the entry block.
1236   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1237     BasicBlock *BB = &*I++;
1238     // If this block doesn't end with an uncond branch, ignore it.
1239     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
1240     if (!BI || !BI->isUnconditional())
1241       continue;
1242
1243     // If the instruction before the branch (skipping debug info) isn't a phi
1244     // node, then other stuff is happening here.
1245     BasicBlock::iterator BBI = BI->getIterator();
1246     if (BBI != BB->begin()) {
1247       --BBI;
1248       while (isa<DbgInfoIntrinsic>(BBI)) {
1249         if (BBI == BB->begin())
1250           break;
1251         --BBI;
1252       }
1253       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
1254         continue;
1255     }
1256
1257     // Do not break infinite loops.
1258     BasicBlock *DestBB = BI->getSuccessor(0);
1259     if (DestBB == BB)
1260       continue;
1261
1262     if (!canMergeBlocks(BB, DestBB))
1263       continue;
1264
1265     eliminateMostlyEmptyBlock(BB);
1266     MadeChange = true;
1267   }
1268   return MadeChange;
1269 }
1270
1271 /// Return true if we can merge BB into DestBB if there is a single
1272 /// unconditional branch between them, and BB contains no other non-phi
1273 /// instructions.
1274 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1275                                     const BasicBlock *DestBB) const {
1276   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1277   // the successor.  If there are more complex condition (e.g. preheaders),
1278   // don't mess around with them.
1279   BasicBlock::const_iterator BBI = BB->begin();
1280   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1281     for (const User *U : PN->users()) {
1282       const Instruction *UI = cast<Instruction>(U);
1283       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1284         return false;
1285       // If User is inside DestBB block and it is a PHINode then check
1286       // incoming value. If incoming value is not from BB then this is
1287       // a complex condition (e.g. preheaders) we want to avoid here.
1288       if (UI->getParent() == DestBB) {
1289         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1290           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1291             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1292             if (Insn && Insn->getParent() == BB &&
1293                 Insn->getParent() != UPN->getIncomingBlock(I))
1294               return false;
1295           }
1296       }
1297     }
1298   }
1299
1300   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1301   // and DestBB may have conflicting incoming values for the block.  If so, we
1302   // can't merge the block.
1303   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1304   if (!DestBBPN) return true;  // no conflict.
1305
1306   // Collect the preds of BB.
1307   SmallPtrSet<const BasicBlock*, 16> BBPreds;
1308   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1309     // It is faster to get preds from a PHI than with pred_iterator.
1310     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1311       BBPreds.insert(BBPN->getIncomingBlock(i));
1312   } else {
1313     BBPreds.insert(pred_begin(BB), pred_end(BB));
1314   }
1315
1316   // Walk the preds of DestBB.
1317   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1318     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1319     if (BBPreds.count(Pred)) {   // Common predecessor?
1320       BBI = DestBB->begin();
1321       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1322         const Value *V1 = PN->getIncomingValueForBlock(Pred);
1323         const Value *V2 = PN->getIncomingValueForBlock(BB);
1324
1325         // If V2 is a phi node in BB, look up what the mapped value will be.
1326         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1327           if (V2PN->getParent() == BB)
1328             V2 = V2PN->getIncomingValueForBlock(Pred);
1329
1330         // If there is a conflict, bail out.
1331         if (V1 != V2) return false;
1332       }
1333     }
1334   }
1335
1336   return true;
1337 }
1338
1339
1340 /// Eliminate a basic block that has only phi's and an unconditional branch in
1341 /// it.
1342 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1343   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1344   BasicBlock *DestBB = BI->getSuccessor(0);
1345
1346   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
1347
1348   // If the destination block has a single pred, then this is a trivial edge,
1349   // just collapse it.
1350   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1351     if (SinglePred != DestBB) {
1352       // Remember if SinglePred was the entry block of the function.  If so, we
1353       // will need to move BB back to the entry position.
1354       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1355       MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
1356
1357       if (isEntry && BB != &BB->getParent()->getEntryBlock())
1358         BB->moveBefore(&BB->getParent()->getEntryBlock());
1359
1360       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1361       return;
1362     }
1363   }
1364
1365   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
1366   // to handle the new incoming edges it is about to have.
1367   PHINode *PN;
1368   for (BasicBlock::iterator BBI = DestBB->begin();
1369        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1370     // Remove the incoming value for BB, and remember it.
1371     Value *InVal = PN->removeIncomingValue(BB, false);
1372
1373     // Two options: either the InVal is a phi node defined in BB or it is some
1374     // value that dominates BB.
1375     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1376     if (InValPhi && InValPhi->getParent() == BB) {
1377       // Add all of the input values of the input PHI as inputs of this phi.
1378       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1379         PN->addIncoming(InValPhi->getIncomingValue(i),
1380                         InValPhi->getIncomingBlock(i));
1381     } else {
1382       // Otherwise, add one instance of the dominating value for each edge that
1383       // we will be adding.
1384       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1385         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1386           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
1387       } else {
1388         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1389           PN->addIncoming(InVal, *PI);
1390       }
1391     }
1392   }
1393
1394   // The PHIs are now updated, change everything that refers to BB to use
1395   // DestBB and remove BB.
1396   BB->replaceAllUsesWith(DestBB);
1397   BB->eraseFromParent();
1398   ++NumBlocksElim;
1399
1400   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1401 }
1402
1403 // Computes a map of base pointer relocation instructions to corresponding
1404 // derived pointer relocation instructions given a vector of all relocate calls
1405 static void computeBaseDerivedRelocateMap(
1406     const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1407     DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1408         &RelocateInstMap) {
1409   // Collect information in two maps: one primarily for locating the base object
1410   // while filling the second map; the second map is the final structure holding
1411   // a mapping between Base and corresponding Derived relocate calls
1412   DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1413   for (auto *ThisRelocate : AllRelocateCalls) {
1414     auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1415                             ThisRelocate->getDerivedPtrIndex());
1416     RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1417   }
1418   for (auto &Item : RelocateIdxMap) {
1419     std::pair<unsigned, unsigned> Key = Item.first;
1420     if (Key.first == Key.second)
1421       // Base relocation: nothing to insert
1422       continue;
1423
1424     GCRelocateInst *I = Item.second;
1425     auto BaseKey = std::make_pair(Key.first, Key.first);
1426
1427     // We're iterating over RelocateIdxMap so we cannot modify it.
1428     auto MaybeBase = RelocateIdxMap.find(BaseKey);
1429     if (MaybeBase == RelocateIdxMap.end())
1430       // TODO: We might want to insert a new base object relocate and gep off
1431       // that, if there are enough derived object relocates.
1432       continue;
1433
1434     RelocateInstMap[MaybeBase->second].push_back(I);
1435   }
1436 }
1437
1438 // Accepts a GEP and extracts the operands into a vector provided they're all
1439 // small integer constants
1440 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1441                                           SmallVectorImpl<Value *> &OffsetV) {
1442   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1443     // Only accept small constant integer operands
1444     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1445     if (!Op || Op->getZExtValue() > 20)
1446       return false;
1447   }
1448
1449   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1450     OffsetV.push_back(GEP->getOperand(i));
1451   return true;
1452 }
1453
1454 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1455 // replace, computes a replacement, and affects it.
1456 static bool
1457 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1458                           const SmallVectorImpl<GCRelocateInst *> &Targets) {
1459   bool MadeChange = false;
1460   for (GCRelocateInst *ToReplace : Targets) {
1461     assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1462            "Not relocating a derived object of the original base object");
1463     if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1464       // A duplicate relocate call. TODO: coalesce duplicates.
1465       continue;
1466     }
1467
1468     if (RelocatedBase->getParent() != ToReplace->getParent()) {
1469       // Base and derived relocates are in different basic blocks.
1470       // In this case transform is only valid when base dominates derived
1471       // relocate. However it would be too expensive to check dominance
1472       // for each such relocate, so we skip the whole transformation.
1473       continue;
1474     }
1475
1476     Value *Base = ToReplace->getBasePtr();
1477     auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1478     if (!Derived || Derived->getPointerOperand() != Base)
1479       continue;
1480
1481     SmallVector<Value *, 2> OffsetV;
1482     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1483       continue;
1484
1485     // Create a Builder and replace the target callsite with a gep
1486     assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
1487
1488     // Insert after RelocatedBase
1489     IRBuilder<> Builder(RelocatedBase->getNextNode());
1490     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1491
1492     // If gc_relocate does not match the actual type, cast it to the right type.
1493     // In theory, there must be a bitcast after gc_relocate if the type does not
1494     // match, and we should reuse it to get the derived pointer. But it could be
1495     // cases like this:
1496     // bb1:
1497     //  ...
1498     //  %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1499     //  br label %merge
1500     //
1501     // bb2:
1502     //  ...
1503     //  %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1504     //  br label %merge
1505     //
1506     // merge:
1507     //  %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1508     //  %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1509     //
1510     // In this case, we can not find the bitcast any more. So we insert a new bitcast
1511     // no matter there is already one or not. In this way, we can handle all cases, and
1512     // the extra bitcast should be optimized away in later passes.
1513     Value *ActualRelocatedBase = RelocatedBase;
1514     if (RelocatedBase->getType() != Base->getType()) {
1515       ActualRelocatedBase =
1516           Builder.CreateBitCast(RelocatedBase, Base->getType());
1517     }
1518     Value *Replacement = Builder.CreateGEP(
1519         Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1520     Replacement->takeName(ToReplace);
1521     // If the newly generated derived pointer's type does not match the original derived
1522     // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
1523     Value *ActualReplacement = Replacement;
1524     if (Replacement->getType() != ToReplace->getType()) {
1525       ActualReplacement =
1526           Builder.CreateBitCast(Replacement, ToReplace->getType());
1527     }
1528     ToReplace->replaceAllUsesWith(ActualReplacement);
1529     ToReplace->eraseFromParent();
1530
1531     MadeChange = true;
1532   }
1533   return MadeChange;
1534 }
1535
1536 // Turns this:
1537 //
1538 // %base = ...
1539 // %ptr = gep %base + 15
1540 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1541 // %base' = relocate(%tok, i32 4, i32 4)
1542 // %ptr' = relocate(%tok, i32 4, i32 5)
1543 // %val = load %ptr'
1544 //
1545 // into this:
1546 //
1547 // %base = ...
1548 // %ptr = gep %base + 15
1549 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1550 // %base' = gc.relocate(%tok, i32 4, i32 4)
1551 // %ptr' = gep %base' + 15
1552 // %val = load %ptr'
1553 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1554   bool MadeChange = false;
1555   SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1556
1557   for (auto *U : I.users())
1558     if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1559       // Collect all the relocate calls associated with a statepoint
1560       AllRelocateCalls.push_back(Relocate);
1561
1562   // We need atleast one base pointer relocation + one derived pointer
1563   // relocation to mangle
1564   if (AllRelocateCalls.size() < 2)
1565     return false;
1566
1567   // RelocateInstMap is a mapping from the base relocate instruction to the
1568   // corresponding derived relocate instructions
1569   DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1570   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1571   if (RelocateInstMap.empty())
1572     return false;
1573
1574   for (auto &Item : RelocateInstMap)
1575     // Item.first is the RelocatedBase to offset against
1576     // Item.second is the vector of Targets to replace
1577     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1578   return MadeChange;
1579 }
1580
1581 /// SinkCast - Sink the specified cast instruction into its user blocks
1582 static bool SinkCast(CastInst *CI) {
1583   BasicBlock *DefBB = CI->getParent();
1584
1585   /// InsertedCasts - Only insert a cast in each block once.
1586   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1587
1588   bool MadeChange = false;
1589   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1590        UI != E; ) {
1591     Use &TheUse = UI.getUse();
1592     Instruction *User = cast<Instruction>(*UI);
1593
1594     // Figure out which BB this cast is used in.  For PHI's this is the
1595     // appropriate predecessor block.
1596     BasicBlock *UserBB = User->getParent();
1597     if (PHINode *PN = dyn_cast<PHINode>(User)) {
1598       UserBB = PN->getIncomingBlock(TheUse);
1599     }
1600
1601     // Preincrement use iterator so we don't invalidate it.
1602     ++UI;
1603
1604     // If the block selected to receive the cast is an EH pad that does not
1605     // allow non-PHI instructions before the terminator, we can't sink the
1606     // cast.
1607     if (UserBB->getTerminator()->isEHPad())
1608       continue;
1609
1610     // If this user is in the same block as the cast, don't change the cast.
1611     if (UserBB == DefBB) continue;
1612
1613     // If we have already inserted a cast into this block, use it.
1614     CastInst *&InsertedCast = InsertedCasts[UserBB];
1615
1616     if (!InsertedCast) {
1617       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1618       assert(InsertPt != UserBB->end());
1619       InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1620                                       CI->getType(), "", &*InsertPt);
1621     }
1622
1623     // Replace a use of the cast with a use of the new cast.
1624     TheUse = InsertedCast;
1625     MadeChange = true;
1626     ++NumCastUses;
1627   }
1628
1629   // If we removed all uses, nuke the cast.
1630   if (CI->use_empty()) {
1631     CI->eraseFromParent();
1632     MadeChange = true;
1633   }
1634
1635   return MadeChange;
1636 }
1637
1638 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1639 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1640 /// reduce the number of virtual registers that must be created and coalesced.
1641 ///
1642 /// Return true if any changes are made.
1643 ///
1644 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1645                                        const DataLayout &DL) {
1646   // If this is a noop copy,
1647   EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1648   EVT DstVT = TLI.getValueType(DL, CI->getType());
1649
1650   // This is an fp<->int conversion?
1651   if (SrcVT.isInteger() != DstVT.isInteger())
1652     return false;
1653
1654   // If this is an extension, it will be a zero or sign extension, which
1655   // isn't a noop.
1656   if (SrcVT.bitsLT(DstVT)) return false;
1657
1658   // If these values will be promoted, find out what they will be promoted
1659   // to.  This helps us consider truncates on PPC as noop copies when they
1660   // are.
1661   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1662       TargetLowering::TypePromoteInteger)
1663     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1664   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1665       TargetLowering::TypePromoteInteger)
1666     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1667
1668   // If, after promotion, these are the same types, this is a noop copy.
1669   if (SrcVT != DstVT)
1670     return false;
1671
1672   return SinkCast(CI);
1673 }
1674
1675 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1676 /// possible.
1677 ///
1678 /// Return true if any changes were made.
1679 static bool CombineUAddWithOverflow(CmpInst *CI) {
1680   Value *A, *B;
1681   Instruction *AddI;
1682   if (!match(CI,
1683              m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1684     return false;
1685
1686   Type *Ty = AddI->getType();
1687   if (!isa<IntegerType>(Ty))
1688     return false;
1689
1690   // We don't want to move around uses of condition values this late, so we we
1691   // check if it is legal to create the call to the intrinsic in the basic
1692   // block containing the icmp:
1693
1694   if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1695     return false;
1696
1697 #ifndef NDEBUG
1698   // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1699   // for now:
1700   if (AddI->hasOneUse())
1701     assert(*AddI->user_begin() == CI && "expected!");
1702 #endif
1703
1704   Module *M = CI->getModule();
1705   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1706
1707   auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1708
1709   auto *UAddWithOverflow =
1710       CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1711   auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1712   auto *Overflow =
1713       ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1714
1715   CI->replaceAllUsesWith(Overflow);
1716   AddI->replaceAllUsesWith(UAdd);
1717   CI->eraseFromParent();
1718   AddI->eraseFromParent();
1719   return true;
1720 }
1721
1722 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1723 /// registers that must be created and coalesced. This is a clear win except on
1724 /// targets with multiple condition code registers (PowerPC), where it might
1725 /// lose; some adjustment may be wanted there.
1726 ///
1727 /// Return true if any changes are made.
1728 static bool SinkCmpExpression(CmpInst *CI) {
1729   BasicBlock *DefBB = CI->getParent();
1730
1731   /// Only insert a cmp in each block once.
1732   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1733
1734   bool MadeChange = false;
1735   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1736        UI != E; ) {
1737     Use &TheUse = UI.getUse();
1738     Instruction *User = cast<Instruction>(*UI);
1739
1740     // Preincrement use iterator so we don't invalidate it.
1741     ++UI;
1742
1743     // Don't bother for PHI nodes.
1744     if (isa<PHINode>(User))
1745       continue;
1746
1747     // Figure out which BB this cmp is used in.
1748     BasicBlock *UserBB = User->getParent();
1749
1750     // If this user is in the same block as the cmp, don't change the cmp.
1751     if (UserBB == DefBB) continue;
1752
1753     // If we have already inserted a cmp into this block, use it.
1754     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1755
1756     if (!InsertedCmp) {
1757       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1758       assert(InsertPt != UserBB->end());
1759       InsertedCmp =
1760           CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1761                           CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1762     }
1763
1764     // Replace a use of the cmp with a use of the new cmp.
1765     TheUse = InsertedCmp;
1766     MadeChange = true;
1767     ++NumCmpUses;
1768   }
1769
1770   // If we removed all uses, nuke the cmp.
1771   if (CI->use_empty()) {
1772     CI->eraseFromParent();
1773     MadeChange = true;
1774   }
1775
1776   return MadeChange;
1777 }
1778
1779 static bool OptimizeCmpExpression(CmpInst *CI) {
1780   if (SinkCmpExpression(CI))
1781     return true;
1782
1783   if (CombineUAddWithOverflow(CI))
1784     return true;
1785
1786   return false;
1787 }
1788
1789 /// Check if the candidates could be combined with a shift instruction, which
1790 /// includes:
1791 /// 1. Truncate instruction
1792 /// 2. And instruction and the imm is a mask of the low bits:
1793 /// imm & (imm+1) == 0
1794 static bool isExtractBitsCandidateUse(Instruction *User) {
1795   if (!isa<TruncInst>(User)) {
1796     if (User->getOpcode() != Instruction::And ||
1797         !isa<ConstantInt>(User->getOperand(1)))
1798       return false;
1799
1800     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1801
1802     if ((Cimm & (Cimm + 1)).getBoolValue())
1803       return false;
1804   }
1805   return true;
1806 }
1807
1808 /// Sink both shift and truncate instruction to the use of truncate's BB.
1809 static bool
1810 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1811                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1812                      const TargetLowering &TLI, const DataLayout &DL) {
1813   BasicBlock *UserBB = User->getParent();
1814   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1815   TruncInst *TruncI = dyn_cast<TruncInst>(User);
1816   bool MadeChange = false;
1817
1818   for (Value::user_iterator TruncUI = TruncI->user_begin(),
1819                             TruncE = TruncI->user_end();
1820        TruncUI != TruncE;) {
1821
1822     Use &TruncTheUse = TruncUI.getUse();
1823     Instruction *TruncUser = cast<Instruction>(*TruncUI);
1824     // Preincrement use iterator so we don't invalidate it.
1825
1826     ++TruncUI;
1827
1828     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1829     if (!ISDOpcode)
1830       continue;
1831
1832     // If the use is actually a legal node, there will not be an
1833     // implicit truncate.
1834     // FIXME: always querying the result type is just an
1835     // approximation; some nodes' legality is determined by the
1836     // operand or other means. There's no good way to find out though.
1837     if (TLI.isOperationLegalOrCustom(
1838             ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1839       continue;
1840
1841     // Don't bother for PHI nodes.
1842     if (isa<PHINode>(TruncUser))
1843       continue;
1844
1845     BasicBlock *TruncUserBB = TruncUser->getParent();
1846
1847     if (UserBB == TruncUserBB)
1848       continue;
1849
1850     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1851     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1852
1853     if (!InsertedShift && !InsertedTrunc) {
1854       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1855       assert(InsertPt != TruncUserBB->end());
1856       // Sink the shift
1857       if (ShiftI->getOpcode() == Instruction::AShr)
1858         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1859                                                    "", &*InsertPt);
1860       else
1861         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1862                                                    "", &*InsertPt);
1863
1864       // Sink the trunc
1865       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1866       TruncInsertPt++;
1867       assert(TruncInsertPt != TruncUserBB->end());
1868
1869       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
1870                                        TruncI->getType(), "", &*TruncInsertPt);
1871
1872       MadeChange = true;
1873
1874       TruncTheUse = InsertedTrunc;
1875     }
1876   }
1877   return MadeChange;
1878 }
1879
1880 /// Sink the shift *right* instruction into user blocks if the uses could
1881 /// potentially be combined with this shift instruction and generate BitExtract
1882 /// instruction. It will only be applied if the architecture supports BitExtract
1883 /// instruction. Here is an example:
1884 /// BB1:
1885 ///   %x.extract.shift = lshr i64 %arg1, 32
1886 /// BB2:
1887 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
1888 /// ==>
1889 ///
1890 /// BB2:
1891 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
1892 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1893 ///
1894 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1895 /// instruction.
1896 /// Return true if any changes are made.
1897 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1898                                 const TargetLowering &TLI,
1899                                 const DataLayout &DL) {
1900   BasicBlock *DefBB = ShiftI->getParent();
1901
1902   /// Only insert instructions in each block once.
1903   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1904
1905   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1906
1907   bool MadeChange = false;
1908   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1909        UI != E;) {
1910     Use &TheUse = UI.getUse();
1911     Instruction *User = cast<Instruction>(*UI);
1912     // Preincrement use iterator so we don't invalidate it.
1913     ++UI;
1914
1915     // Don't bother for PHI nodes.
1916     if (isa<PHINode>(User))
1917       continue;
1918
1919     if (!isExtractBitsCandidateUse(User))
1920       continue;
1921
1922     BasicBlock *UserBB = User->getParent();
1923
1924     if (UserBB == DefBB) {
1925       // If the shift and truncate instruction are in the same BB. The use of
1926       // the truncate(TruncUse) may still introduce another truncate if not
1927       // legal. In this case, we would like to sink both shift and truncate
1928       // instruction to the BB of TruncUse.
1929       // for example:
1930       // BB1:
1931       // i64 shift.result = lshr i64 opnd, imm
1932       // trunc.result = trunc shift.result to i16
1933       //
1934       // BB2:
1935       //   ----> We will have an implicit truncate here if the architecture does
1936       //   not have i16 compare.
1937       // cmp i16 trunc.result, opnd2
1938       //
1939       if (isa<TruncInst>(User) && shiftIsLegal
1940           // If the type of the truncate is legal, no trucate will be
1941           // introduced in other basic blocks.
1942           &&
1943           (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1944         MadeChange =
1945             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1946
1947       continue;
1948     }
1949     // If we have already inserted a shift into this block, use it.
1950     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1951
1952     if (!InsertedShift) {
1953       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1954       assert(InsertPt != UserBB->end());
1955
1956       if (ShiftI->getOpcode() == Instruction::AShr)
1957         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1958                                                    "", &*InsertPt);
1959       else
1960         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1961                                                    "", &*InsertPt);
1962
1963       MadeChange = true;
1964     }
1965
1966     // Replace a use of the shift with a use of the new shift.
1967     TheUse = InsertedShift;
1968   }
1969
1970   // If we removed all uses, nuke the shift.
1971   if (ShiftI->use_empty())
1972     ShiftI->eraseFromParent();
1973
1974   return MadeChange;
1975 }
1976
1977 // Translate a masked load intrinsic like
1978 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1979 //                               <16 x i1> %mask, <16 x i32> %passthru)
1980 // to a chain of basic blocks, with loading element one-by-one if
1981 // the appropriate mask bit is set
1982 //
1983 //  %1 = bitcast i8* %addr to i32*
1984 //  %2 = extractelement <16 x i1> %mask, i32 0
1985 //  %3 = icmp eq i1 %2, true
1986 //  br i1 %3, label %cond.load, label %else
1987 //
1988 //cond.load:                                        ; preds = %0
1989 //  %4 = getelementptr i32* %1, i32 0
1990 //  %5 = load i32* %4
1991 //  %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1992 //  br label %else
1993 //
1994 //else:                                             ; preds = %0, %cond.load
1995 //  %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1996 //  %7 = extractelement <16 x i1> %mask, i32 1
1997 //  %8 = icmp eq i1 %7, true
1998 //  br i1 %8, label %cond.load1, label %else2
1999 //
2000 //cond.load1:                                       ; preds = %else
2001 //  %9 = getelementptr i32* %1, i32 1
2002 //  %10 = load i32* %9
2003 //  %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
2004 //  br label %else2
2005 //
2006 //else2:                                            ; preds = %else, %cond.load1
2007 //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2008 //  %12 = extractelement <16 x i1> %mask, i32 2
2009 //  %13 = icmp eq i1 %12, true
2010 //  br i1 %13, label %cond.load4, label %else5
2011 //
2012 static void ScalarizeMaskedLoad(CallInst *CI) {
2013   Value *Ptr  = CI->getArgOperand(0);
2014   Value *Alignment = CI->getArgOperand(1);
2015   Value *Mask = CI->getArgOperand(2);
2016   Value *Src0 = CI->getArgOperand(3);
2017
2018   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2019   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2020   assert(VecType && "Unexpected return type of masked load intrinsic");
2021
2022   Type *EltTy = CI->getType()->getVectorElementType();
2023
2024   IRBuilder<> Builder(CI->getContext());
2025   Instruction *InsertPt = CI;
2026   BasicBlock *IfBlock = CI->getParent();
2027   BasicBlock *CondBlock = nullptr;
2028   BasicBlock *PrevIfBlock = CI->getParent();
2029
2030   Builder.SetInsertPoint(InsertPt);
2031   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2032
2033   // Short-cut if the mask is all-true.
2034   bool IsAllOnesMask = isa<Constant>(Mask) &&
2035     cast<Constant>(Mask)->isAllOnesValue();
2036
2037   if (IsAllOnesMask) {
2038     Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
2039     CI->replaceAllUsesWith(NewI);
2040     CI->eraseFromParent();
2041     return;
2042   }
2043
2044   // Adjust alignment for the scalar instruction.
2045   AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
2046   // Bitcast %addr fron i8* to EltTy*
2047   Type *NewPtrType =
2048     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2049   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2050   unsigned VectorWidth = VecType->getNumElements();
2051
2052   Value *UndefVal = UndefValue::get(VecType);
2053
2054   // The result vector
2055   Value *VResult = UndefVal;
2056
2057   if (isa<ConstantVector>(Mask)) {
2058     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2059       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2060           continue;
2061       Value *Gep =
2062           Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2063       LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2064       VResult = Builder.CreateInsertElement(VResult, Load,
2065                                             Builder.getInt32(Idx));
2066     }
2067     Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2068     CI->replaceAllUsesWith(NewI);
2069     CI->eraseFromParent();
2070     return;
2071   }
2072
2073   PHINode *Phi = nullptr;
2074   Value *PrevPhi = UndefVal;
2075
2076   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2077
2078     // Fill the "else" block, created in the previous iteration
2079     //
2080     //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2081     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2082     //  %to_load = icmp eq i1 %mask_1, true
2083     //  br i1 %to_load, label %cond.load, label %else
2084     //
2085     if (Idx > 0) {
2086       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2087       Phi->addIncoming(VResult, CondBlock);
2088       Phi->addIncoming(PrevPhi, PrevIfBlock);
2089       PrevPhi = Phi;
2090       VResult = Phi;
2091     }
2092
2093     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2094     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2095                                     ConstantInt::get(Predicate->getType(), 1));
2096
2097     // Create "cond" block
2098     //
2099     //  %EltAddr = getelementptr i32* %1, i32 0
2100     //  %Elt = load i32* %EltAddr
2101     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2102     //
2103     CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
2104     Builder.SetInsertPoint(InsertPt);
2105
2106     Value *Gep =
2107         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2108     LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2109     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
2110
2111     // Create "else" block, fill it in the next iteration
2112     BasicBlock *NewIfBlock =
2113         CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2114     Builder.SetInsertPoint(InsertPt);
2115     Instruction *OldBr = IfBlock->getTerminator();
2116     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2117     OldBr->eraseFromParent();
2118     PrevIfBlock = IfBlock;
2119     IfBlock = NewIfBlock;
2120   }
2121
2122   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2123   Phi->addIncoming(VResult, CondBlock);
2124   Phi->addIncoming(PrevPhi, PrevIfBlock);
2125   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2126   CI->replaceAllUsesWith(NewI);
2127   CI->eraseFromParent();
2128 }
2129
2130 // Translate a masked store intrinsic, like
2131 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
2132 //                               <16 x i1> %mask)
2133 // to a chain of basic blocks, that stores element one-by-one if
2134 // the appropriate mask bit is set
2135 //
2136 //   %1 = bitcast i8* %addr to i32*
2137 //   %2 = extractelement <16 x i1> %mask, i32 0
2138 //   %3 = icmp eq i1 %2, true
2139 //   br i1 %3, label %cond.store, label %else
2140 //
2141 // cond.store:                                       ; preds = %0
2142 //   %4 = extractelement <16 x i32> %val, i32 0
2143 //   %5 = getelementptr i32* %1, i32 0
2144 //   store i32 %4, i32* %5
2145 //   br label %else
2146 //
2147 // else:                                             ; preds = %0, %cond.store
2148 //   %6 = extractelement <16 x i1> %mask, i32 1
2149 //   %7 = icmp eq i1 %6, true
2150 //   br i1 %7, label %cond.store1, label %else2
2151 //
2152 // cond.store1:                                      ; preds = %else
2153 //   %8 = extractelement <16 x i32> %val, i32 1
2154 //   %9 = getelementptr i32* %1, i32 1
2155 //   store i32 %8, i32* %9
2156 //   br label %else2
2157 //   . . .
2158 static void ScalarizeMaskedStore(CallInst *CI) {
2159   Value *Src = CI->getArgOperand(0);
2160   Value *Ptr  = CI->getArgOperand(1);
2161   Value *Alignment = CI->getArgOperand(2);
2162   Value *Mask = CI->getArgOperand(3);
2163
2164   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2165   VectorType *VecType = dyn_cast<VectorType>(Src->getType());
2166   assert(VecType && "Unexpected data type in masked store intrinsic");
2167
2168   Type *EltTy = VecType->getElementType();
2169
2170   IRBuilder<> Builder(CI->getContext());
2171   Instruction *InsertPt = CI;
2172   BasicBlock *IfBlock = CI->getParent();
2173   Builder.SetInsertPoint(InsertPt);
2174   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2175
2176   // Short-cut if the mask is all-true.
2177   bool IsAllOnesMask = isa<Constant>(Mask) &&
2178     cast<Constant>(Mask)->isAllOnesValue();
2179
2180   if (IsAllOnesMask) {
2181     Builder.CreateAlignedStore(Src, Ptr, AlignVal);
2182     CI->eraseFromParent();
2183     return;
2184   }
2185
2186   // Adjust alignment for the scalar instruction.
2187   AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
2188   // Bitcast %addr fron i8* to EltTy*
2189   Type *NewPtrType =
2190     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2191   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2192   unsigned VectorWidth = VecType->getNumElements();
2193
2194   if (isa<ConstantVector>(Mask)) {
2195     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2196       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2197           continue;
2198       Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2199       Value *Gep =
2200           Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2201       Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2202     }
2203     CI->eraseFromParent();
2204     return;
2205   }
2206
2207   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2208
2209     // Fill the "else" block, created in the previous iteration
2210     //
2211     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2212     //  %to_store = icmp eq i1 %mask_1, true
2213     //  br i1 %to_store, label %cond.store, label %else
2214     //
2215     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2216     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2217                                     ConstantInt::get(Predicate->getType(), 1));
2218
2219     // Create "cond" block
2220     //
2221     //  %OneElt = extractelement <16 x i32> %Src, i32 Idx
2222     //  %EltAddr = getelementptr i32* %1, i32 0
2223     //  %store i32 %OneElt, i32* %EltAddr
2224     //
2225     BasicBlock *CondBlock =
2226         IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
2227     Builder.SetInsertPoint(InsertPt);
2228
2229     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2230     Value *Gep =
2231         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2232     Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2233
2234     // Create "else" block, fill it in the next iteration
2235     BasicBlock *NewIfBlock =
2236         CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2237     Builder.SetInsertPoint(InsertPt);
2238     Instruction *OldBr = IfBlock->getTerminator();
2239     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2240     OldBr->eraseFromParent();
2241     IfBlock = NewIfBlock;
2242   }
2243   CI->eraseFromParent();
2244 }
2245
2246 // Translate a masked gather intrinsic like
2247 // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
2248 //                               <16 x i1> %Mask, <16 x i32> %Src)
2249 // to a chain of basic blocks, with loading element one-by-one if
2250 // the appropriate mask bit is set
2251 //
2252 // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
2253 // % Mask0 = extractelement <16 x i1> %Mask, i32 0
2254 // % ToLoad0 = icmp eq i1 % Mask0, true
2255 // br i1 % ToLoad0, label %cond.load, label %else
2256 //
2257 // cond.load:
2258 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2259 // % Load0 = load i32, i32* % Ptr0, align 4
2260 // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
2261 // br label %else
2262 //
2263 // else:
2264 // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
2265 // % Mask1 = extractelement <16 x i1> %Mask, i32 1
2266 // % ToLoad1 = icmp eq i1 % Mask1, true
2267 // br i1 % ToLoad1, label %cond.load1, label %else2
2268 //
2269 // cond.load1:
2270 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2271 // % Load1 = load i32, i32* % Ptr1, align 4
2272 // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
2273 // br label %else2
2274 // . . .
2275 // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
2276 // ret <16 x i32> %Result
2277 static void ScalarizeMaskedGather(CallInst *CI) {
2278   Value *Ptrs = CI->getArgOperand(0);
2279   Value *Alignment = CI->getArgOperand(1);
2280   Value *Mask = CI->getArgOperand(2);
2281   Value *Src0 = CI->getArgOperand(3);
2282
2283   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2284
2285   assert(VecType && "Unexpected return type of masked load intrinsic");
2286
2287   IRBuilder<> Builder(CI->getContext());
2288   Instruction *InsertPt = CI;
2289   BasicBlock *IfBlock = CI->getParent();
2290   BasicBlock *CondBlock = nullptr;
2291   BasicBlock *PrevIfBlock = CI->getParent();
2292   Builder.SetInsertPoint(InsertPt);
2293   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2294
2295   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2296
2297   Value *UndefVal = UndefValue::get(VecType);
2298
2299   // The result vector
2300   Value *VResult = UndefVal;
2301   unsigned VectorWidth = VecType->getNumElements();
2302
2303   // Shorten the way if the mask is a vector of constants.
2304   bool IsConstMask = isa<ConstantVector>(Mask);
2305
2306   if (IsConstMask) {
2307     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2308       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2309         continue;
2310       Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2311                                                 "Ptr" + Twine(Idx));
2312       LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2313                                                  "Load" + Twine(Idx));
2314       VResult = Builder.CreateInsertElement(VResult, Load,
2315                                             Builder.getInt32(Idx),
2316                                             "Res" + Twine(Idx));
2317     }
2318     Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2319     CI->replaceAllUsesWith(NewI);
2320     CI->eraseFromParent();
2321     return;
2322   }
2323
2324   PHINode *Phi = nullptr;
2325   Value *PrevPhi = UndefVal;
2326
2327   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2328
2329     // Fill the "else" block, created in the previous iteration
2330     //
2331     //  %Mask1 = extractelement <16 x i1> %Mask, i32 1
2332     //  %ToLoad1 = icmp eq i1 %Mask1, true
2333     //  br i1 %ToLoad1, label %cond.load, label %else
2334     //
2335     if (Idx > 0) {
2336       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2337       Phi->addIncoming(VResult, CondBlock);
2338       Phi->addIncoming(PrevPhi, PrevIfBlock);
2339       PrevPhi = Phi;
2340       VResult = Phi;
2341     }
2342
2343     Value *Predicate = Builder.CreateExtractElement(Mask,
2344                                                     Builder.getInt32(Idx),
2345                                                     "Mask" + Twine(Idx));
2346     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2347                                     ConstantInt::get(Predicate->getType(), 1),
2348                                     "ToLoad" + Twine(Idx));
2349
2350     // Create "cond" block
2351     //
2352     //  %EltAddr = getelementptr i32* %1, i32 0
2353     //  %Elt = load i32* %EltAddr
2354     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2355     //
2356     CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
2357     Builder.SetInsertPoint(InsertPt);
2358
2359     Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2360                                               "Ptr" + Twine(Idx));
2361     LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2362                                                "Load" + Twine(Idx));
2363     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
2364                                           "Res" + Twine(Idx));
2365
2366     // Create "else" block, fill it in the next iteration
2367     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2368     Builder.SetInsertPoint(InsertPt);
2369     Instruction *OldBr = IfBlock->getTerminator();
2370     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2371     OldBr->eraseFromParent();
2372     PrevIfBlock = IfBlock;
2373     IfBlock = NewIfBlock;
2374   }
2375
2376   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2377   Phi->addIncoming(VResult, CondBlock);
2378   Phi->addIncoming(PrevPhi, PrevIfBlock);
2379   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2380   CI->replaceAllUsesWith(NewI);
2381   CI->eraseFromParent();
2382 }
2383
2384 // Translate a masked scatter intrinsic, like
2385 // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
2386 //                                  <16 x i1> %Mask)
2387 // to a chain of basic blocks, that stores element one-by-one if
2388 // the appropriate mask bit is set.
2389 //
2390 // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
2391 // % Mask0 = extractelement <16 x i1> % Mask, i32 0
2392 // % ToStore0 = icmp eq i1 % Mask0, true
2393 // br i1 %ToStore0, label %cond.store, label %else
2394 //
2395 // cond.store:
2396 // % Elt0 = extractelement <16 x i32> %Src, i32 0
2397 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2398 // store i32 %Elt0, i32* % Ptr0, align 4
2399 // br label %else
2400 //
2401 // else:
2402 // % Mask1 = extractelement <16 x i1> % Mask, i32 1
2403 // % ToStore1 = icmp eq i1 % Mask1, true
2404 // br i1 % ToStore1, label %cond.store1, label %else2
2405 //
2406 // cond.store1:
2407 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2408 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2409 // store i32 % Elt1, i32* % Ptr1, align 4
2410 // br label %else2
2411 //   . . .
2412 static void ScalarizeMaskedScatter(CallInst *CI) {
2413   Value *Src = CI->getArgOperand(0);
2414   Value *Ptrs = CI->getArgOperand(1);
2415   Value *Alignment = CI->getArgOperand(2);
2416   Value *Mask = CI->getArgOperand(3);
2417
2418   assert(isa<VectorType>(Src->getType()) &&
2419          "Unexpected data type in masked scatter intrinsic");
2420   assert(isa<VectorType>(Ptrs->getType()) &&
2421          isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
2422          "Vector of pointers is expected in masked scatter intrinsic");
2423
2424   IRBuilder<> Builder(CI->getContext());
2425   Instruction *InsertPt = CI;
2426   BasicBlock *IfBlock = CI->getParent();
2427   Builder.SetInsertPoint(InsertPt);
2428   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2429
2430   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2431   unsigned VectorWidth = Src->getType()->getVectorNumElements();
2432
2433   // Shorten the way if the mask is a vector of constants.
2434   bool IsConstMask = isa<ConstantVector>(Mask);
2435
2436   if (IsConstMask) {
2437     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2438       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2439         continue;
2440       Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2441                                                    "Elt" + Twine(Idx));
2442       Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2443                                                 "Ptr" + Twine(Idx));
2444       Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2445     }
2446     CI->eraseFromParent();
2447     return;
2448   }
2449   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2450     // Fill the "else" block, created in the previous iteration
2451     //
2452     //  % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
2453     //  % ToStore = icmp eq i1 % Mask1, true
2454     //  br i1 % ToStore, label %cond.store, label %else
2455     //
2456     Value *Predicate = Builder.CreateExtractElement(Mask,
2457                                                     Builder.getInt32(Idx),
2458                                                     "Mask" + Twine(Idx));
2459     Value *Cmp =
2460        Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2461                           ConstantInt::get(Predicate->getType(), 1),
2462                           "ToStore" + Twine(Idx));
2463
2464     // Create "cond" block
2465     //
2466     //  % Elt1 = extractelement <16 x i32> %Src, i32 1
2467     //  % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2468     //  %store i32 % Elt1, i32* % Ptr1
2469     //
2470     BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2471     Builder.SetInsertPoint(InsertPt);
2472
2473     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2474                                                  "Elt" + Twine(Idx));
2475     Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2476                                               "Ptr" + Twine(Idx));
2477     Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2478
2479     // Create "else" block, fill it in the next iteration
2480     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2481     Builder.SetInsertPoint(InsertPt);
2482     Instruction *OldBr = IfBlock->getTerminator();
2483     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2484     OldBr->eraseFromParent();
2485     IfBlock = NewIfBlock;
2486   }
2487   CI->eraseFromParent();
2488 }
2489
2490 /// If counting leading or trailing zeros is an expensive operation and a zero
2491 /// input is defined, add a check for zero to avoid calling the intrinsic.
2492 ///
2493 /// We want to transform:
2494 ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2495 ///
2496 /// into:
2497 ///   entry:
2498 ///     %cmpz = icmp eq i64 %A, 0
2499 ///     br i1 %cmpz, label %cond.end, label %cond.false
2500 ///   cond.false:
2501 ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2502 ///     br label %cond.end
2503 ///   cond.end:
2504 ///     %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2505 ///
2506 /// If the transform is performed, return true and set ModifiedDT to true.
2507 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2508                                   const TargetLowering *TLI,
2509                                   const DataLayout *DL,
2510                                   bool &ModifiedDT) {
2511   if (!TLI || !DL)
2512     return false;
2513
2514   // If a zero input is undefined, it doesn't make sense to despeculate that.
2515   if (match(CountZeros->getOperand(1), m_One()))
2516     return false;
2517
2518   // If it's cheap to speculate, there's nothing to do.
2519   auto IntrinsicID = CountZeros->getIntrinsicID();
2520   if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2521       (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2522     return false;
2523
2524   // Only handle legal scalar cases. Anything else requires too much work.
2525   Type *Ty = CountZeros->getType();
2526   unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
2527   if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
2528     return false;
2529
2530   // The intrinsic will be sunk behind a compare against zero and branch.
2531   BasicBlock *StartBlock = CountZeros->getParent();
2532   BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2533
2534   // Create another block after the count zero intrinsic. A PHI will be added
2535   // in this block to select the result of the intrinsic or the bit-width
2536   // constant if the input to the intrinsic is zero.
2537   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2538   BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2539
2540   // Set up a builder to create a compare, conditional branch, and PHI.
2541   IRBuilder<> Builder(CountZeros->getContext());
2542   Builder.SetInsertPoint(StartBlock->getTerminator());
2543   Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2544
2545   // Replace the unconditional branch that was created by the first split with
2546   // a compare against zero and a conditional branch.
2547   Value *Zero = Constant::getNullValue(Ty);
2548   Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2549   Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2550   StartBlock->getTerminator()->eraseFromParent();
2551
2552   // Create a PHI in the end block to select either the output of the intrinsic
2553   // or the bit width of the operand.
2554   Builder.SetInsertPoint(&EndBlock->front());
2555   PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2556   CountZeros->replaceAllUsesWith(PN);
2557   Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2558   PN->addIncoming(BitWidth, StartBlock);
2559   PN->addIncoming(CountZeros, CallBlock);
2560
2561   // We are explicitly handling the zero case, so we can set the intrinsic's
2562   // undefined zero argument to 'true'. This will also prevent reprocessing the
2563   // intrinsic; we only despeculate when a zero input is defined.
2564   CountZeros->setArgOperand(1, Builder.getTrue());
2565   ModifiedDT = true;
2566   return true;
2567 }
2568
2569 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
2570   BasicBlock *BB = CI->getParent();
2571
2572   // Lower inline assembly if we can.
2573   // If we found an inline asm expession, and if the target knows how to
2574   // lower it to normal LLVM code, do so now.
2575   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2576     if (TLI->ExpandInlineAsm(CI)) {
2577       // Avoid invalidating the iterator.
2578       CurInstIterator = BB->begin();
2579       // Avoid processing instructions out of order, which could cause
2580       // reuse before a value is defined.
2581       SunkAddrs.clear();
2582       return true;
2583     }
2584     // Sink address computing for memory operands into the block.
2585     if (optimizeInlineAsmInst(CI))
2586       return true;
2587   }
2588
2589   // Align the pointer arguments to this call if the target thinks it's a good
2590   // idea
2591   unsigned MinSize, PrefAlign;
2592   if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2593     for (auto &Arg : CI->arg_operands()) {
2594       // We want to align both objects whose address is used directly and
2595       // objects whose address is used in casts and GEPs, though it only makes
2596       // sense for GEPs if the offset is a multiple of the desired alignment and
2597       // if size - offset meets the size threshold.
2598       if (!Arg->getType()->isPointerTy())
2599         continue;
2600       APInt Offset(DL->getPointerSizeInBits(
2601                        cast<PointerType>(Arg->getType())->getAddressSpace()),
2602                    0);
2603       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2604       uint64_t Offset2 = Offset.getLimitedValue();
2605       if ((Offset2 & (PrefAlign-1)) != 0)
2606         continue;
2607       AllocaInst *AI;
2608       if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2609           DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2610         AI->setAlignment(PrefAlign);
2611       // Global variables can only be aligned if they are defined in this
2612       // object (i.e. they are uniquely initialized in this object), and
2613       // over-aligning global variables that have an explicit section is
2614       // forbidden.
2615       GlobalVariable *GV;
2616       if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2617           GV->getAlignment() < PrefAlign &&
2618           DL->getTypeAllocSize(GV->getType()->getElementType()) >=
2619               MinSize + Offset2)
2620         GV->setAlignment(PrefAlign);
2621     }
2622     // If this is a memcpy (or similar) then we may be able to improve the
2623     // alignment
2624     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2625       unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2626       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2627         Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2628       if (Align > MI->getAlignment())
2629         MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2630     }
2631   }
2632
2633   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2634   if (II) {
2635     switch (II->getIntrinsicID()) {
2636     default: break;
2637     case Intrinsic::objectsize: {
2638       // Lower all uses of llvm.objectsize.*
2639       bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
2640       Type *ReturnTy = CI->getType();
2641       Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
2642
2643       // Substituting this can cause recursive simplifications, which can
2644       // invalidate our iterator.  Use a WeakVH to hold onto it in case this
2645       // happens.
2646       WeakVH IterHandle(&*CurInstIterator);
2647
2648       replaceAndRecursivelySimplify(CI, RetVal,
2649                                     TLInfo, nullptr);
2650
2651       // If the iterator instruction was recursively deleted, start over at the
2652       // start of the block.
2653       if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
2654         CurInstIterator = BB->begin();
2655         SunkAddrs.clear();
2656       }
2657       return true;
2658     }
2659     case Intrinsic::masked_load: {
2660       // Scalarize unsupported vector masked load
2661       if (!TTI->isLegalMaskedLoad(CI->getType())) {
2662         ScalarizeMaskedLoad(CI);
2663         ModifiedDT = true;
2664         return true;
2665       }
2666       return false;
2667     }
2668     case Intrinsic::masked_store: {
2669       if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
2670         ScalarizeMaskedStore(CI);
2671         ModifiedDT = true;
2672         return true;
2673       }
2674       return false;
2675     }
2676     case Intrinsic::masked_gather: {
2677       if (!TTI->isLegalMaskedGather(CI->getType())) {
2678         ScalarizeMaskedGather(CI);
2679         ModifiedDT = true;
2680         return true;
2681       }
2682       return false;
2683     }
2684     case Intrinsic::masked_scatter: {
2685       if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
2686         ScalarizeMaskedScatter(CI);
2687         ModifiedDT = true;
2688         return true;
2689       }
2690       return false;
2691     }
2692     case Intrinsic::aarch64_stlxr:
2693     case Intrinsic::aarch64_stxr: {
2694       ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2695       if (!ExtVal || !ExtVal->hasOneUse() ||
2696           ExtVal->getParent() == CI->getParent())
2697         return false;
2698       // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2699       ExtVal->moveBefore(CI);
2700       // Mark this instruction as "inserted by CGP", so that other
2701       // optimizations don't touch it.
2702       InsertedInsts.insert(ExtVal);
2703       return true;
2704     }
2705     case Intrinsic::invariant_group_barrier:
2706       II->replaceAllUsesWith(II->getArgOperand(0));
2707       II->eraseFromParent();
2708       return true;
2709
2710     case Intrinsic::cttz:
2711     case Intrinsic::ctlz:
2712       // If counting zeros is expensive, try to avoid it.
2713       return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2714     }
2715
2716     if (TLI) {
2717       // Unknown address space.
2718       // TODO: Target hook to pick which address space the intrinsic cares
2719       // about?
2720       unsigned AddrSpace = ~0u;
2721       SmallVector<Value*, 2> PtrOps;
2722       Type *AccessTy;
2723       if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
2724         while (!PtrOps.empty())
2725           if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
2726             return true;
2727     }
2728   }
2729
2730   // From here on out we're working with named functions.
2731   if (!CI->getCalledFunction()) return false;
2732
2733   // Lower all default uses of _chk calls.  This is very similar
2734   // to what InstCombineCalls does, but here we are only lowering calls
2735   // to fortified library functions (e.g. __memcpy_chk) that have the default
2736   // "don't know" as the objectsize.  Anything else should be left alone.
2737   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2738   if (Value *V = Simplifier.optimizeCall(CI)) {
2739     CI->replaceAllUsesWith(V);
2740     CI->eraseFromParent();
2741     return true;
2742   }
2743   return false;
2744 }
2745
2746 /// Look for opportunities to duplicate return instructions to the predecessor
2747 /// to enable tail call optimizations. The case it is currently looking for is:
2748 /// @code
2749 /// bb0:
2750 ///   %tmp0 = tail call i32 @f0()
2751 ///   br label %return
2752 /// bb1:
2753 ///   %tmp1 = tail call i32 @f1()
2754 ///   br label %return
2755 /// bb2:
2756 ///   %tmp2 = tail call i32 @f2()
2757 ///   br label %return
2758 /// return:
2759 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2760 ///   ret i32 %retval
2761 /// @endcode
2762 ///
2763 /// =>
2764 ///
2765 /// @code
2766 /// bb0:
2767 ///   %tmp0 = tail call i32 @f0()
2768 ///   ret i32 %tmp0
2769 /// bb1:
2770 ///   %tmp1 = tail call i32 @f1()
2771 ///   ret i32 %tmp1
2772 /// bb2:
2773 ///   %tmp2 = tail call i32 @f2()
2774 ///   ret i32 %tmp2
2775 /// @endcode
2776 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
2777   if (!TLI)
2778     return false;
2779
2780   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
2781   if (!RI)
2782     return false;
2783
2784   PHINode *PN = nullptr;
2785   BitCastInst *BCI = nullptr;
2786   Value *V = RI->getReturnValue();
2787   if (V) {
2788     BCI = dyn_cast<BitCastInst>(V);
2789     if (BCI)
2790       V = BCI->getOperand(0);
2791
2792     PN = dyn_cast<PHINode>(V);
2793     if (!PN)
2794       return false;
2795   }
2796
2797   if (PN && PN->getParent() != BB)
2798     return false;
2799
2800   // It's not safe to eliminate the sign / zero extension of the return value.
2801   // See llvm::isInTailCallPosition().
2802   const Function *F = BB->getParent();
2803   AttributeSet CallerAttrs = F->getAttributes();
2804   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
2805       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
2806     return false;
2807
2808   // Make sure there are no instructions between the PHI and return, or that the
2809   // return is the first instruction in the block.
2810   if (PN) {
2811     BasicBlock::iterator BI = BB->begin();
2812     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
2813     if (&*BI == BCI)
2814       // Also skip over the bitcast.
2815       ++BI;
2816     if (&*BI != RI)
2817       return false;
2818   } else {
2819     BasicBlock::iterator BI = BB->begin();
2820     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2821     if (&*BI != RI)
2822       return false;
2823   }
2824
2825   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2826   /// call.
2827   SmallVector<CallInst*, 4> TailCalls;
2828   if (PN) {
2829     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2830       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2831       // Make sure the phi value is indeed produced by the tail call.
2832       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2833           TLI->mayBeEmittedAsTailCall(CI))
2834         TailCalls.push_back(CI);
2835     }
2836   } else {
2837     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
2838     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
2839       if (!VisitedBBs.insert(*PI).second)
2840         continue;
2841
2842       BasicBlock::InstListType &InstList = (*PI)->getInstList();
2843       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2844       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
2845       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2846       if (RI == RE)
2847         continue;
2848
2849       CallInst *CI = dyn_cast<CallInst>(&*RI);
2850       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
2851         TailCalls.push_back(CI);
2852     }
2853   }
2854
2855   bool Changed = false;
2856   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2857     CallInst *CI = TailCalls[i];
2858     CallSite CS(CI);
2859
2860     // Conservatively require the attributes of the call to match those of the
2861     // return. Ignore noalias because it doesn't affect the call sequence.
2862     AttributeSet CalleeAttrs = CS.getAttributes();
2863     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
2864           removeAttribute(Attribute::NoAlias) !=
2865         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
2866           removeAttribute(Attribute::NoAlias))
2867       continue;
2868
2869     // Make sure the call instruction is followed by an unconditional branch to
2870     // the return block.
2871     BasicBlock *CallBB = CI->getParent();
2872     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2873     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2874       continue;
2875
2876     // Duplicate the return into CallBB.
2877     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
2878     ModifiedDT = Changed = true;
2879     ++NumRetsDup;
2880   }
2881
2882   // If we eliminated all predecessors of the block, delete the block now.
2883   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
2884     BB->eraseFromParent();
2885
2886   return Changed;
2887 }
2888
2889 //===----------------------------------------------------------------------===//
2890 // Memory Optimization
2891 //===----------------------------------------------------------------------===//
2892
2893 namespace {
2894
2895 /// This is an extended version of TargetLowering::AddrMode
2896 /// which holds actual Value*'s for register values.
2897 struct ExtAddrMode : public TargetLowering::AddrMode {
2898   Value *BaseReg;
2899   Value *ScaledReg;
2900   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
2901   void print(raw_ostream &OS) const;
2902   void dump() const;
2903
2904   bool operator==(const ExtAddrMode& O) const {
2905     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2906            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2907            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2908   }
2909 };
2910
2911 #ifndef NDEBUG
2912 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2913   AM.print(OS);
2914   return OS;
2915 }
2916 #endif
2917
2918 void ExtAddrMode::print(raw_ostream &OS) const {
2919   bool NeedPlus = false;
2920   OS << "[";
2921   if (BaseGV) {
2922     OS << (NeedPlus ? " + " : "")
2923        << "GV:";
2924     BaseGV->printAsOperand(OS, /*PrintType=*/false);
2925     NeedPlus = true;
2926   }
2927
2928   if (BaseOffs) {
2929     OS << (NeedPlus ? " + " : "")
2930        << BaseOffs;
2931     NeedPlus = true;
2932   }
2933
2934   if (BaseReg) {
2935     OS << (NeedPlus ? " + " : "")
2936        << "Base:";
2937     BaseReg->printAsOperand(OS, /*PrintType=*/false);
2938     NeedPlus = true;
2939   }
2940   if (Scale) {
2941     OS << (NeedPlus ? " + " : "")
2942        << Scale << "*";
2943     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2944   }
2945
2946   OS << ']';
2947 }
2948
2949 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2950 void ExtAddrMode::dump() const {
2951   print(dbgs());
2952   dbgs() << '\n';
2953 }
2954 #endif
2955
2956 /// \brief This class provides transaction based operation on the IR.
2957 /// Every change made through this class is recorded in the internal state and
2958 /// can be undone (rollback) until commit is called.
2959 class TypePromotionTransaction {
2960
2961   /// \brief This represents the common interface of the individual transaction.
2962   /// Each class implements the logic for doing one specific modification on
2963   /// the IR via the TypePromotionTransaction.
2964   class TypePromotionAction {
2965   protected:
2966     /// The Instruction modified.
2967     Instruction *Inst;
2968
2969   public:
2970     /// \brief Constructor of the action.
2971     /// The constructor performs the related action on the IR.
2972     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2973
2974     virtual ~TypePromotionAction() {}
2975
2976     /// \brief Undo the modification done by this action.
2977     /// When this method is called, the IR must be in the same state as it was
2978     /// before this action was applied.
2979     /// \pre Undoing the action works if and only if the IR is in the exact same
2980     /// state as it was directly after this action was applied.
2981     virtual void undo() = 0;
2982
2983     /// \brief Advocate every change made by this action.
2984     /// When the results on the IR of the action are to be kept, it is important
2985     /// to call this function, otherwise hidden information may be kept forever.
2986     virtual void commit() {
2987       // Nothing to be done, this action is not doing anything.
2988     }
2989   };
2990
2991   /// \brief Utility to remember the position of an instruction.
2992   class InsertionHandler {
2993     /// Position of an instruction.
2994     /// Either an instruction:
2995     /// - Is the first in a basic block: BB is used.
2996     /// - Has a previous instructon: PrevInst is used.
2997     union {
2998       Instruction *PrevInst;
2999       BasicBlock *BB;
3000     } Point;
3001     /// Remember whether or not the instruction had a previous instruction.
3002     bool HasPrevInstruction;
3003
3004   public:
3005     /// \brief Record the position of \p Inst.
3006     InsertionHandler(Instruction *Inst) {
3007       BasicBlock::iterator It = Inst->getIterator();
3008       HasPrevInstruction = (It != (Inst->getParent()->begin()));
3009       if (HasPrevInstruction)
3010         Point.PrevInst = &*--It;
3011       else
3012         Point.BB = Inst->getParent();
3013     }
3014
3015     /// \brief Insert \p Inst at the recorded position.
3016     void insert(Instruction *Inst) {
3017       if (HasPrevInstruction) {
3018         if (Inst->getParent())
3019           Inst->removeFromParent();
3020         Inst->insertAfter(Point.PrevInst);
3021       } else {
3022         Instruction *Position = &*Point.BB->getFirstInsertionPt();
3023         if (Inst->getParent())
3024           Inst->moveBefore(Position);
3025         else
3026           Inst->insertBefore(Position);
3027       }
3028     }
3029   };
3030
3031   /// \brief Move an instruction before another.
3032   class InstructionMoveBefore : public TypePromotionAction {
3033     /// Original position of the instruction.
3034     InsertionHandler Position;
3035
3036   public:
3037     /// \brief Move \p Inst before \p Before.
3038     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
3039         : TypePromotionAction(Inst), Position(Inst) {
3040       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
3041       Inst->moveBefore(Before);
3042     }
3043
3044     /// \brief Move the instruction back to its original position.
3045     void undo() override {
3046       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3047       Position.insert(Inst);
3048     }
3049   };
3050
3051   /// \brief Set the operand of an instruction with a new value.
3052   class OperandSetter : public TypePromotionAction {
3053     /// Original operand of the instruction.
3054     Value *Origin;
3055     /// Index of the modified instruction.
3056     unsigned Idx;
3057
3058   public:
3059     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
3060     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3061         : TypePromotionAction(Inst), Idx(Idx) {
3062       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3063                    << "for:" << *Inst << "\n"
3064                    << "with:" << *NewVal << "\n");
3065       Origin = Inst->getOperand(Idx);
3066       Inst->setOperand(Idx, NewVal);
3067     }
3068
3069     /// \brief Restore the original value of the instruction.
3070     void undo() override {
3071       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3072                    << "for: " << *Inst << "\n"
3073                    << "with: " << *Origin << "\n");
3074       Inst->setOperand(Idx, Origin);
3075     }
3076   };
3077
3078   /// \brief Hide the operands of an instruction.
3079   /// Do as if this instruction was not using any of its operands.
3080   class OperandsHider : public TypePromotionAction {
3081     /// The list of original operands.
3082     SmallVector<Value *, 4> OriginalValues;
3083
3084   public:
3085     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
3086     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3087       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3088       unsigned NumOpnds = Inst->getNumOperands();
3089       OriginalValues.reserve(NumOpnds);
3090       for (unsigned It = 0; It < NumOpnds; ++It) {
3091         // Save the current operand.
3092         Value *Val = Inst->getOperand(It);
3093         OriginalValues.push_back(Val);
3094         // Set a dummy one.
3095         // We could use OperandSetter here, but that would imply an overhead
3096         // that we are not willing to pay.
3097         Inst->setOperand(It, UndefValue::get(Val->getType()));
3098       }
3099     }
3100
3101     /// \brief Restore the original list of uses.
3102     void undo() override {
3103       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3104       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3105         Inst->setOperand(It, OriginalValues[It]);
3106     }
3107   };
3108
3109   /// \brief Build a truncate instruction.
3110   class TruncBuilder : public TypePromotionAction {
3111     Value *Val;
3112   public:
3113     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
3114     /// result.
3115     /// trunc Opnd to Ty.
3116     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3117       IRBuilder<> Builder(Opnd);
3118       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3119       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3120     }
3121
3122     /// \brief Get the built value.
3123     Value *getBuiltValue() { return Val; }
3124
3125     /// \brief Remove the built instruction.
3126     void undo() override {
3127       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3128       if (Instruction *IVal = dyn_cast<Instruction>(Val))
3129         IVal->eraseFromParent();
3130     }
3131   };
3132
3133   /// \brief Build a sign extension instruction.
3134   class SExtBuilder : public TypePromotionAction {
3135     Value *Val;
3136   public:
3137     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
3138     /// result.
3139     /// sext Opnd to Ty.
3140     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3141         : TypePromotionAction(InsertPt) {
3142       IRBuilder<> Builder(InsertPt);
3143       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3144       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3145     }
3146
3147     /// \brief Get the built value.
3148     Value *getBuiltValue() { return Val; }
3149
3150     /// \brief Remove the built instruction.
3151     void undo() override {
3152       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3153       if (Instruction *IVal = dyn_cast<Instruction>(Val))
3154         IVal->eraseFromParent();
3155     }
3156   };
3157
3158   /// \brief Build a zero extension instruction.
3159   class ZExtBuilder : public TypePromotionAction {
3160     Value *Val;
3161   public:
3162     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
3163     /// result.
3164     /// zext Opnd to Ty.
3165     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3166         : TypePromotionAction(InsertPt) {
3167       IRBuilder<> Builder(InsertPt);
3168       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3169       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3170     }
3171
3172     /// \brief Get the built value.
3173     Value *getBuiltValue() { return Val; }
3174
3175     /// \brief Remove the built instruction.
3176     void undo() override {
3177       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3178       if (Instruction *IVal = dyn_cast<Instruction>(Val))
3179         IVal->eraseFromParent();
3180     }
3181   };
3182
3183   /// \brief Mutate an instruction to another type.
3184   class TypeMutator : public TypePromotionAction {
3185     /// Record the original type.
3186     Type *OrigTy;
3187
3188   public:
3189     /// \brief Mutate the type of \p Inst into \p NewTy.
3190     TypeMutator(Instruction *Inst, Type *NewTy)
3191         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3192       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3193                    << "\n");
3194       Inst->mutateType(NewTy);
3195     }
3196
3197     /// \brief Mutate the instruction back to its original type.
3198     void undo() override {
3199       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3200                    << "\n");
3201       Inst->mutateType(OrigTy);
3202     }
3203   };
3204
3205   /// \brief Replace the uses of an instruction by another instruction.
3206   class UsesReplacer : public TypePromotionAction {
3207     /// Helper structure to keep track of the replaced uses.
3208     struct InstructionAndIdx {
3209       /// The instruction using the instruction.
3210       Instruction *Inst;
3211       /// The index where this instruction is used for Inst.
3212       unsigned Idx;
3213       InstructionAndIdx(Instruction *Inst, unsigned Idx)
3214           : Inst(Inst), Idx(Idx) {}
3215     };
3216
3217     /// Keep track of the original uses (pair Instruction, Index).
3218     SmallVector<InstructionAndIdx, 4> OriginalUses;
3219     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
3220
3221   public:
3222     /// \brief Replace all the use of \p Inst by \p New.
3223     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
3224       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3225                    << "\n");
3226       // Record the original uses.
3227       for (Use &U : Inst->uses()) {
3228         Instruction *UserI = cast<Instruction>(U.getUser());
3229         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3230       }
3231       // Now, we can replace the uses.
3232       Inst->replaceAllUsesWith(New);
3233     }
3234
3235     /// \brief Reassign the original uses of Inst to Inst.
3236     void undo() override {
3237       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3238       for (use_iterator UseIt = OriginalUses.begin(),
3239                         EndIt = OriginalUses.end();
3240            UseIt != EndIt; ++UseIt) {
3241         UseIt->Inst->setOperand(UseIt->Idx, Inst);
3242       }
3243     }
3244   };
3245
3246   /// \brief Remove an instruction from the IR.
3247   class InstructionRemover : public TypePromotionAction {
3248     /// Original position of the instruction.
3249     InsertionHandler Inserter;
3250     /// Helper structure to hide all the link to the instruction. In other
3251     /// words, this helps to do as if the instruction was removed.
3252     OperandsHider Hider;
3253     /// Keep track of the uses replaced, if any.
3254     UsesReplacer *Replacer;
3255
3256   public:
3257     /// \brief Remove all reference of \p Inst and optinally replace all its
3258     /// uses with New.
3259     /// \pre If !Inst->use_empty(), then New != nullptr
3260     InstructionRemover(Instruction *Inst, Value *New = nullptr)
3261         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3262           Replacer(nullptr) {
3263       if (New)
3264         Replacer = new UsesReplacer(Inst, New);
3265       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3266       Inst->removeFromParent();
3267     }
3268
3269     ~InstructionRemover() override { delete Replacer; }
3270
3271     /// \brief Really remove the instruction.
3272     void commit() override { delete Inst; }
3273
3274     /// \brief Resurrect the instruction and reassign it to the proper uses if
3275     /// new value was provided when build this action.
3276     void undo() override {
3277       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3278       Inserter.insert(Inst);
3279       if (Replacer)
3280         Replacer->undo();
3281       Hider.undo();
3282     }
3283   };
3284
3285 public:
3286   /// Restoration point.
3287   /// The restoration point is a pointer to an action instead of an iterator
3288   /// because the iterator may be invalidated but not the pointer.
3289   typedef const TypePromotionAction *ConstRestorationPt;
3290   /// Advocate every changes made in that transaction.
3291   void commit();
3292   /// Undo all the changes made after the given point.
3293   void rollback(ConstRestorationPt Point);
3294   /// Get the current restoration point.
3295   ConstRestorationPt getRestorationPoint() const;
3296
3297   /// \name API for IR modification with state keeping to support rollback.
3298   /// @{
3299   /// Same as Instruction::setOperand.
3300   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3301   /// Same as Instruction::eraseFromParent.
3302   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3303   /// Same as Value::replaceAllUsesWith.
3304   void replaceAllUsesWith(Instruction *Inst, Value *New);
3305   /// Same as Value::mutateType.
3306   void mutateType(Instruction *Inst, Type *NewTy);
3307   /// Same as IRBuilder::createTrunc.
3308   Value *createTrunc(Instruction *Opnd, Type *Ty);
3309   /// Same as IRBuilder::createSExt.
3310   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3311   /// Same as IRBuilder::createZExt.
3312   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3313   /// Same as Instruction::moveBefore.
3314   void moveBefore(Instruction *Inst, Instruction *Before);
3315   /// @}
3316
3317 private:
3318   /// The ordered list of actions made so far.
3319   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3320   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
3321 };
3322
3323 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3324                                           Value *NewVal) {
3325   Actions.push_back(
3326       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
3327 }
3328
3329 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3330                                                 Value *NewVal) {
3331   Actions.push_back(
3332       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
3333 }
3334
3335 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3336                                                   Value *New) {
3337   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3338 }
3339
3340 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3341   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3342 }
3343
3344 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3345                                              Type *Ty) {
3346   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3347   Value *Val = Ptr->getBuiltValue();
3348   Actions.push_back(std::move(Ptr));
3349   return Val;
3350 }
3351
3352 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3353                                             Value *Opnd, Type *Ty) {
3354   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3355   Value *Val = Ptr->getBuiltValue();
3356   Actions.push_back(std::move(Ptr));
3357   return Val;
3358 }
3359
3360 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3361                                             Value *Opnd, Type *Ty) {
3362   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3363   Value *Val = Ptr->getBuiltValue();
3364   Actions.push_back(std::move(Ptr));
3365   return Val;
3366 }
3367
3368 void TypePromotionTransaction::moveBefore(Instruction *Inst,
3369                                           Instruction *Before) {
3370   Actions.push_back(
3371       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
3372 }
3373
3374 TypePromotionTransaction::ConstRestorationPt
3375 TypePromotionTransaction::getRestorationPoint() const {
3376   return !Actions.empty() ? Actions.back().get() : nullptr;
3377 }
3378
3379 void TypePromotionTransaction::commit() {
3380   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
3381        ++It)
3382     (*It)->commit();
3383   Actions.clear();
3384 }
3385
3386 void TypePromotionTransaction::rollback(
3387     TypePromotionTransaction::ConstRestorationPt Point) {
3388   while (!Actions.empty() && Point != Actions.back().get()) {
3389     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3390     Curr->undo();
3391   }
3392 }
3393
3394 /// \brief A helper class for matching addressing modes.
3395 ///
3396 /// This encapsulates the logic for matching the target-legal addressing modes.
3397 class AddressingModeMatcher {
3398   SmallVectorImpl<Instruction*> &AddrModeInsts;
3399   const TargetMachine &TM;
3400   const TargetLowering &TLI;
3401   const DataLayout &DL;
3402
3403   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3404   /// the memory instruction that we're computing this address for.
3405   Type *AccessTy;
3406   unsigned AddrSpace;
3407   Instruction *MemoryInst;
3408
3409   /// This is the addressing mode that we're building up. This is
3410   /// part of the return value of this addressing mode matching stuff.
3411   ExtAddrMode &AddrMode;
3412
3413   /// The instructions inserted by other CodeGenPrepare optimizations.
3414   const SetOfInstrs &InsertedInsts;
3415   /// A map from the instructions to their type before promotion.
3416   InstrToOrigTy &PromotedInsts;
3417   /// The ongoing transaction where every action should be registered.
3418   TypePromotionTransaction &TPT;
3419
3420   /// This is set to true when we should not do profitability checks.
3421   /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3422   bool IgnoreProfitability;
3423
3424   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
3425                         const TargetMachine &TM, Type *AT, unsigned AS,
3426                         Instruction *MI, ExtAddrMode &AM,
3427                         const SetOfInstrs &InsertedInsts,
3428                         InstrToOrigTy &PromotedInsts,
3429                         TypePromotionTransaction &TPT)
3430       : AddrModeInsts(AMI), TM(TM),
3431         TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
3432                  ->getTargetLowering()),
3433         DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3434         MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3435         PromotedInsts(PromotedInsts), TPT(TPT) {
3436     IgnoreProfitability = false;
3437   }
3438 public:
3439
3440   /// Find the maximal addressing mode that a load/store of V can fold,
3441   /// give an access type of AccessTy.  This returns a list of involved
3442   /// instructions in AddrModeInsts.
3443   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3444   /// optimizations.
3445   /// \p PromotedInsts maps the instructions to their type before promotion.
3446   /// \p The ongoing transaction where every action should be registered.
3447   static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
3448                            Instruction *MemoryInst,
3449                            SmallVectorImpl<Instruction*> &AddrModeInsts,
3450                            const TargetMachine &TM,
3451                            const SetOfInstrs &InsertedInsts,
3452                            InstrToOrigTy &PromotedInsts,
3453                            TypePromotionTransaction &TPT) {
3454     ExtAddrMode Result;
3455
3456     bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
3457                                          MemoryInst, Result, InsertedInsts,
3458                                          PromotedInsts, TPT).matchAddr(V, 0);
3459     (void)Success; assert(Success && "Couldn't select *anything*?");
3460     return Result;
3461   }
3462 private:
3463   bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3464   bool matchAddr(Value *V, unsigned Depth);
3465   bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
3466                           bool *MovedAway = nullptr);
3467   bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3468                                             ExtAddrMode &AMBefore,
3469                                             ExtAddrMode &AMAfter);
3470   bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3471   bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3472                              Value *PromotedOperand) const;
3473 };
3474
3475 /// Try adding ScaleReg*Scale to the current addressing mode.
3476 /// Return true and update AddrMode if this addr mode is legal for the target,
3477 /// false if not.
3478 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3479                                              unsigned Depth) {
3480   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3481   // mode.  Just process that directly.
3482   if (Scale == 1)
3483     return matchAddr(ScaleReg, Depth);
3484
3485   // If the scale is 0, it takes nothing to add this.
3486   if (Scale == 0)
3487     return true;
3488
3489   // If we already have a scale of this value, we can add to it, otherwise, we