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