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