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