1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
59 using namespace llvm::PatternMatch;
61 #define DEBUG_TYPE "codegenprepare"
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 "
68 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
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");
83 static cl::opt<bool> DisableBranchOpts(
84 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
85 cl::desc("Disable branch optimizations in CodeGenPrepare"));
88 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
89 cl::desc("Disable GC optimizations in CodeGenPrepare"));
91 static cl::opt<bool> DisableSelectToBranch(
92 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
93 cl::desc("Disable select to branch conversion."));
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."));
99 static cl::opt<bool> EnableAndCmpSinking(
100 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
101 cl::desc("Enable sinkinig and/cmp into branches."));
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"));
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"));
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 "
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"));
122 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
123 typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
124 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
125 class TypePromotionTransaction;
127 class CodeGenPrepare : public FunctionPass {
128 const TargetMachine *TM;
129 const TargetLowering *TLI;
130 const TargetTransformInfo *TTI;
131 const TargetLibraryInfo *TLInfo;
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;
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;
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;
148 /// True if CFG is modified in any way.
151 /// True if optimizing for size.
154 /// DataLayout for the Function being processed.
155 const DataLayout *DL;
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());
163 bool runOnFunction(Function &F) override;
165 const char *getPassName() const override { return "CodeGen Prepare"; }
167 void getAnalysisUsage(AnalysisUsage &AU) const override {
168 AU.addPreserved<DominatorTreeWrapperPass>();
169 AU.addRequired<TargetLibraryInfoWrapperPass>();
170 AU.addRequired<TargetTransformInfoWrapperPass>();
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,
196 const SmallVectorImpl<Instruction *> &Exts,
197 unsigned CreatedInstCost);
198 bool splitBranchCondition(Function &F);
199 bool simplifyOffsetableRelocate(Instruction &I);
200 void stripInvariantGroupMetadata(Instruction &I);
204 char CodeGenPrepare::ID = 0;
205 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
206 "Optimize for code generation", false, false)
208 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
209 return new CodeGenPrepare(TM);
214 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal);
215 Value* GetUntaintedAddress(Value* CurrentAddress);
217 // The depth we trace down a variable to look for its dependence set.
218 const unsigned kDependenceDepth = 4;
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) {
231 if (!InsertOnlyLeafNodes && !isa<Constant>(Val)) {
235 // Cannot go deeper. Insert the leaf nodes.
236 if (InsertOnlyLeafNodes && !isa<Constant>(Val)) {
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.
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);
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);
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);
285 // Be conservative. Add it and be done with it.
291 } else if (isa<Constant>(Val)) {
292 // Not interested in constant values. Done.
295 // Be conservative. Add it and be done with it.
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;
310 case Type::FloatTyID:
311 case Type::DoubleTyID: {
312 CastOp = Instruction::FPToSI;
315 case Type::PointerTyID: {
316 CastOp = Instruction::PtrToInt;
322 return Builder.CreateCast(CastOp, DepVal, TargetIntegerType);
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.
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;
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()) {
364 // Looks like it's not been tainted.
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) {
387 // No need to check the operands.
388 auto* AndDepInst = dyn_cast<Instruction>(OrAddress->getOperand(0));
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) {
409 return AndInst->getOperand(0);
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.
421 Value* Operand = Dep;
423 auto* Inst = dyn_cast<Instruction>(Operand);
424 if (Inst == nullptr) {
425 // Non-instruction type does not have condition dependence.
428 if (Inst->getOpcode() == Instruction::ICmp) {
431 if (Inst->getNumOperands() != 1) {
434 Operand = Inst->getOperand(0);
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;
451 IncludingSet DepSet1;
453 // Look for more depths for the including set.
454 recursivelyFindDependence(&DepSet1, Val1, false /*Insert all visited nodes*/,
456 recursivelyFindDependence(&DepSet2, Val2, true /*Only insert leaf nodes*/,
459 auto set_inclusion = [](IncludingSet FullSet, IncludedSet Subset) {
460 for (auto* Dep : Subset) {
461 if (0 == FullSet.count(Dep)) {
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"; });
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*/,
485 if (DepSet.size() == 1) {
486 return *DepSet.begin();
493 // This function actually taints 'DepVal' to the address to 'SI'. If the
495 // of 'SI' already depends on whatever 'DepVal' depends on, this function
496 // doesn't do anything and returns false. Otherwise, returns true.
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*;
508 // This is a more concrete example:
510 // %0 = load i32, i32* @y, align 4, !tbaa !1
511 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
512 // %1 = sext i1 %cmp to i32
513 // %2 = ptrtoint i32* @x to i32
514 // %3 = and i32 %1, 0
515 // %4 = or i32 %3, %2
516 // %5 = inttoptr i32 %4 to i32*
517 // store i32 1, i32* %5, align 4
518 bool taintStoreAddress(StoreInst* SI, Value* DepVal,
519 const char* calling_func = __builtin_FUNCTION()) {
520 DEBUG(dbgs() << "Called from " << calling_func << '\n');
521 IRBuilder<true, NoFolder> Builder(SI);
522 BasicBlock* BB = SI->getParent();
523 Value* Address = SI->getPointerOperand();
524 Type* TargetIntegerType =
525 IntegerType::get(Address->getContext(),
526 BB->getModule()->getDataLayout().getPointerSizeInBits());
528 // Does SI's address already depends on whatever 'DepVal' depends on?
529 if (StoreAddressDependOnValue(SI, DepVal)) {
533 // Figure out if there's a root variable 'DepVal' depends on. For example, we
534 // can extract "getelementptr inbounds %struct, %struct* %0, i64 0, i32 123"
535 // to be "%struct* %0" since all other operands are constant.
536 DepVal = getRootDependence(DepVal);
538 // Is this already a dependence-tainted store?
539 Value* OldDep = getDependence(Address);
541 // The address of 'SI' has already been tainted. Just need to absorb the
542 // DepVal to the existing dependence in the address of SI.
543 Instruction* AndDep = getAndDependence(Address);
544 IRBuilder<true, NoFolder> Builder(AndDep);
545 Value* NewDep = nullptr;
546 if (DepVal->getType() == AndDep->getType()) {
547 NewDep = Builder.CreateAnd(OldDep, DepVal);
549 NewDep = Builder.CreateAnd(
550 OldDep, createCast(Builder, DepVal, TargetIntegerType));
553 auto* NewDepInst = dyn_cast<Instruction>(NewDep);
555 // Use the new AND instruction as the dependence
556 AndDep->setOperand(0, NewDep);
560 // SI's address has not been tainted. Now taint it with 'DepVal'.
561 Value* CastDepToInt = createCast(Builder, DepVal, TargetIntegerType);
562 Value* PtrToIntCast = Builder.CreatePtrToInt(Address, TargetIntegerType);
564 Builder.CreateAnd(CastDepToInt, ConstantInt::get(TargetIntegerType, 0));
565 auto AndInst = dyn_cast<Instruction>(AndDepVal);
566 // XXX-comment: The original IR InstCombiner would change our and instruction
567 // to a select and then the back end optimize the condition out. We attach a
568 // flag to instructions and set it here to inform the InstCombiner to not to
569 // touch this and instruction at all.
570 Value* OrAddr = Builder.CreateOr(AndDepVal, PtrToIntCast);
571 Value* NewAddr = Builder.CreateIntToPtr(OrAddr, Address->getType());
573 DEBUG(dbgs() << "[taintStoreAddress]\n"
574 << "Original store: " << *SI << '\n');
575 SI->setOperand(1, NewAddr);
578 DEBUG(dbgs() << "\tTargetIntegerType: " << *TargetIntegerType << '\n'
579 << "\tCast dependence value to integer: " << *CastDepToInt
581 << "\tCast address to integer: " << *PtrToIntCast << '\n'
582 << "\tAnd dependence value: " << *AndDepVal << '\n'
583 << "\tOr address: " << *OrAddr << '\n'
584 << "\tCast or instruction to address: " << *NewAddr << "\n\n");
589 // Looks for the previous store in the if block --- 'BrBB', which makes the
590 // speculative store 'StoreToHoist' safe.
591 Value* getSpeculativeStoreInPrevBB(StoreInst* StoreToHoist, BasicBlock* BrBB) {
592 assert(StoreToHoist && "StoreToHoist must be a real store");
594 Value* StorePtr = StoreToHoist->getPointerOperand();
596 // Look for a store to the same pointer in BrBB.
597 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), RE = BrBB->rend();
599 Instruction* CurI = &*RI;
601 StoreInst* SI = dyn_cast<StoreInst>(CurI);
602 // Found the previous store make sure it stores to the same location.
603 // XXX-update: If the previous store's original untainted address are the
604 // same as 'StorePtr', we are also good to hoist the store.
605 if (SI && (SI->getPointerOperand() == StorePtr ||
606 GetUntaintedAddress(SI->getPointerOperand()) == StorePtr)) {
607 // Found the previous store, return its value operand.
613 "We should not reach here since this store is safe to speculate");
616 // XXX-comment: Returns true if it changes the code, false otherwise (the branch
617 // condition already depends on 'DepVal'.
618 bool taintConditionalBranch(BranchInst* BI, Value* DepVal) {
619 assert(BI->isConditional());
620 auto* Cond = BI->getOperand(0);
621 if (dependenceSetInclusion(Cond, DepVal)) {
622 // The dependence/ordering is self-evident.
626 IRBuilder<true, NoFolder> Builder(BI);
628 Builder.CreateAnd(DepVal, ConstantInt::get(DepVal->getType(), 0));
630 Builder.CreateTrunc(AndDep, IntegerType::get(DepVal->getContext(), 1));
631 auto* OrCond = Builder.CreateOr(TruncAndDep, Cond);
632 BI->setOperand(0, OrCond);
635 DEBUG(dbgs() << "\tTainted branch condition:\n" << *BI->getParent());
640 bool ConditionalBranchDependsOnValue(BranchInst* BI, Value* DepVal) {
641 assert(BI->isConditional());
642 auto* Cond = BI->getOperand(0);
643 return dependenceSetInclusion(Cond, DepVal);
646 // XXX-update: For a relaxed load 'LI', find the first immediate atomic store or
647 // the first conditional branch. Returns nullptr if there's no such immediately
648 // following store/branch instructions, which we can only enforce the load with
650 Instruction* findFirstStoreCondBranchInst(LoadInst* LI) {
651 // In some situations, relaxed loads can be left as is:
652 // 1. The relaxed load is used to calculate the address of the immediate
654 // 2. The relaxed load is used as a condition in the immediate following
655 // condition, and there are no stores in between. This is actually quite
657 // int r1 = x.load(relaxed);
659 // y.store(1, relaxed);
661 // However, in this function, we don't deal with them directly. Instead, we
662 // just find the immediate following store/condition branch and return it.
664 auto* BB = LI->getParent();
666 auto BBI = BasicBlock::iterator(LI);
669 for (; BBI != BE; BBI++) {
670 auto* Inst = dyn_cast<Instruction>(&*BBI);
671 if (Inst == nullptr) {
674 if (Inst->getOpcode() == Instruction::Store) {
676 } else if (Inst->getOpcode() == Instruction::Br) {
677 auto* BrInst = dyn_cast<BranchInst>(Inst);
678 if (BrInst->isConditional()) {
681 // Reinitialize iterators with the destination of the unconditional
683 BB = BrInst->getSuccessor(0);
696 // XXX-comment: Returns whether the code has been changed.
697 bool taintMonotonicLoads(const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
698 bool Changed = false;
699 for (auto* LI : MonotonicLoadInsts) {
700 auto* FirstInst = findFirstStoreCondBranchInst(LI);
701 if (FirstInst == nullptr) {
702 // We don't seem to be able to taint a following store/conditional branch
703 // instruction. Simply make it acquire.
704 DEBUG(dbgs() << "[RelaxedLoad]: Transformed to acquire load\n"
706 LI->setOrdering(Acquire);
710 // Taint 'FirstInst', which could be a store or a condition branch
712 if (FirstInst->getOpcode() == Instruction::Store) {
713 Changed |= taintStoreAddress(dyn_cast<StoreInst>(FirstInst), LI);
714 } else if (FirstInst->getOpcode() == Instruction::Br) {
715 Changed |= taintConditionalBranch(dyn_cast<BranchInst>(FirstInst), LI);
717 assert(false && "findFirstStoreCondBranchInst() should return a "
718 "store/condition branch instruction");
724 // Inserts a fake conditional branch right after the instruction 'SplitInst',
725 // and the branch condition is 'Condition'. 'SplitInst' will be placed in the
726 // newly created block.
727 void AddFakeConditionalBranch(Instruction* SplitInst, Value* Condition) {
728 auto* BB = SplitInst->getParent();
729 TerminatorInst* ThenTerm = nullptr;
730 TerminatorInst* ElseTerm = nullptr;
731 SplitBlockAndInsertIfThenElse(Condition, SplitInst, &ThenTerm, &ElseTerm);
732 assert(ThenTerm && ElseTerm &&
733 "Then/Else terminators cannot be empty after basic block spliting");
734 auto* ThenBB = ThenTerm->getParent();
735 auto* ElseBB = ElseTerm->getParent();
736 auto* TailBB = ThenBB->getSingleSuccessor();
737 assert(TailBB && "Tail block cannot be empty after basic block spliting");
739 ThenBB->disableCanEliminateBlock();
740 ThenBB->disableCanEliminateBlock();
741 TailBB->disableCanEliminateBlock();
742 ThenBB->setName(BB->getName() + "Then.Fake");
743 ElseBB->setName(BB->getName() + "Else.Fake");
744 DEBUG(dbgs() << "Add fake conditional branch:\n"
746 << *ThenBB << "Else Block:\n"
750 // Returns true if the code is changed, and false otherwise.
751 void TaintRelaxedLoads(LoadInst* LI) {
752 IRBuilder<true, NoFolder> Builder(LI->getNextNode());
753 auto* FakeCondition = dyn_cast<Instruction>(Builder.CreateICmp(
754 CmpInst::ICMP_EQ, LI, Constant::getNullValue(LI->getType())));
755 AddFakeConditionalBranch(FakeCondition->getNextNode(), FakeCondition);
758 // XXX-comment: Returns whether the code has been changed.
759 bool AddFakeConditionalBranchAfterMonotonicLoads(
760 const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
761 bool Changed = false;
762 for (auto* LI : MonotonicLoadInsts) {
763 auto* FirstInst = findFirstStoreCondBranchInst(LI);
764 if (FirstInst != nullptr) {
765 if (FirstInst->getOpcode() == Instruction::Store) {
766 if (StoreAddressDependOnValue(dyn_cast<StoreInst>(FirstInst), LI)) {
769 } else if (FirstInst->getOpcode() == Instruction::Br) {
770 if (ConditionalBranchDependsOnValue(dyn_cast<BranchInst>(FirstInst),
775 dbgs() << "FirstInst=" << *FirstInst << "\n";
776 assert(false && "findFirstStoreCondBranchInst() should return a "
777 "store/condition branch instruction");
781 // We really need to process the relaxed load now.
782 TaintRelaxedLoads(LI);
788 /**** Implementations of public methods for dependence tainting ****/
789 Value* GetUntaintedAddress(Value* CurrentAddress) {
790 auto* OrAddress = getOrAddress(CurrentAddress);
791 if (OrAddress == nullptr) {
792 // Is it tainted by a select instruction?
793 auto* Inst = dyn_cast<Instruction>(CurrentAddress);
794 if (nullptr != Inst && Inst->getOpcode() == Instruction::Select) {
795 // A selection instruction.
796 if (Inst->getOperand(1) == Inst->getOperand(2)) {
797 return Inst->getOperand(1);
801 return CurrentAddress;
803 Value* ActualAddress = nullptr;
805 auto* CastToInt = dyn_cast<Instruction>(OrAddress->getOperand(1));
806 if (CastToInt && CastToInt->getOpcode() == Instruction::PtrToInt) {
807 return CastToInt->getOperand(0);
809 // This should be a IntToPtr constant expression.
810 ConstantExpr* PtrToIntExpr =
811 dyn_cast<ConstantExpr>(OrAddress->getOperand(1));
812 if (PtrToIntExpr && PtrToIntExpr->getOpcode() == Instruction::PtrToInt) {
813 return PtrToIntExpr->getOperand(0);
817 // Looks like it's not been dependence-tainted. Returns itself.
818 return CurrentAddress;
821 MemoryLocation GetUntaintedMemoryLocation(StoreInst* SI) {
823 SI->getAAMetadata(AATags);
824 const auto& DL = SI->getModule()->getDataLayout();
825 const auto* OriginalAddr = GetUntaintedAddress(SI->getPointerOperand());
826 DEBUG(if (OriginalAddr != SI->getPointerOperand()) {
827 dbgs() << "[GetUntaintedMemoryLocation]\n"
828 << "Storing address: " << *SI->getPointerOperand()
829 << "\nUntainted address: " << *OriginalAddr << "\n";
831 return MemoryLocation(OriginalAddr,
832 DL.getTypeStoreSize(SI->getValueOperand()->getType()),
836 bool TaintDependenceToStore(StoreInst* SI, Value* DepVal) {
837 if (dependenceSetInclusion(SI, DepVal)) {
841 bool tainted = taintStoreAddress(SI, DepVal);
846 bool TaintDependenceToStoreAddress(StoreInst* SI, Value* DepVal) {
847 if (dependenceSetInclusion(SI->getPointerOperand(), DepVal)) {
851 bool tainted = taintStoreAddress(SI, DepVal);
856 bool CompressTaintedStore(BasicBlock* BB) {
857 // This function looks for windows of adajcent stores in 'BB' that satisfy the
858 // following condition (and then do optimization):
859 // *Addr(d1) = v1, d1 is a condition and is the only dependence the store's
860 // address depends on && Dep(v1) includes Dep(d1);
861 // *Addr(d2) = v2, d2 is a condition and is the only dependnece the store's
862 // address depends on && Dep(v2) includes Dep(d2) &&
863 // Dep(d2) includes Dep(d1);
865 // *Addr(dN) = vN, dN is a condition and is the only dependence the store's
866 // address depends on && Dep(dN) includes Dep(d"N-1").
868 // As a result, Dep(dN) includes [Dep(d1) V ... V Dep(d"N-1")], so we can
869 // safely transform the above to the following. In between these stores, we
870 // can omit untainted stores to the same address 'Addr' since they internally
871 // have dependence on the previous stores on the same address.
876 for (auto BI = BB->begin(), BE = BB->end(); BI != BE; BI++) {
877 // Look for the first store in such a window of adajacent stores.
878 auto* FirstSI = dyn_cast<StoreInst>(&*BI);
883 // The first store in the window must be tainted.
884 auto* UntaintedAddress = GetUntaintedAddress(FirstSI->getPointerOperand());
885 if (UntaintedAddress == FirstSI->getPointerOperand()) {
889 // The first store's address must directly depend on and only depend on a
891 auto* FirstSIDepCond = getConditionDependence(FirstSI->getPointerOperand());
892 if (nullptr == FirstSIDepCond) {
896 // Dep(first store's storing value) includes Dep(tainted dependence).
897 if (!dependenceSetInclusion(FirstSI->getValueOperand(), FirstSIDepCond)) {
901 // Look for subsequent stores to the same address that satisfy the condition
902 // of "compressing the dependence".
903 SmallVector<StoreInst*, 8> AdajacentStores;
904 AdajacentStores.push_back(FirstSI);
905 auto BII = BasicBlock::iterator(FirstSI);
906 for (BII++; BII != BE; BII++) {
907 auto* CurrSI = dyn_cast<StoreInst>(&*BII);
909 if (BII->mayHaveSideEffects()) {
910 // Be conservative. Instructions with side effects are similar to
917 auto* OrigAddress = GetUntaintedAddress(CurrSI->getPointerOperand());
918 auto* CurrSIDepCond = getConditionDependence(CurrSI->getPointerOperand());
919 // All other stores must satisfy either:
920 // A. 'CurrSI' is an untainted store to the same address, or
921 // B. the combination of the following 5 subconditions:
923 // 2. Untainted address is the same as the group's address;
924 // 3. The address is tainted with a sole value which is a condition;
925 // 4. The storing value depends on the condition in 3.
926 // 5. The condition in 3 depends on the previous stores dependence
929 // Condition A. Should ignore this store directly.
930 if (OrigAddress == CurrSI->getPointerOperand() &&
931 OrigAddress == UntaintedAddress) {
934 // Check condition B.
935 Value* Cond = nullptr;
936 if (OrigAddress == CurrSI->getPointerOperand() ||
937 OrigAddress != UntaintedAddress || CurrSIDepCond == nullptr ||
938 !dependenceSetInclusion(CurrSI->getValueOperand(), CurrSIDepCond)) {
939 // Check condition 1, 2, 3 & 4.
943 // Check condition 5.
944 StoreInst* PrevSI = AdajacentStores[AdajacentStores.size() - 1];
945 auto* PrevSIDepCond = getConditionDependence(PrevSI->getPointerOperand());
946 assert(PrevSIDepCond &&
947 "Store in the group must already depend on a condtion");
948 if (!dependenceSetInclusion(CurrSIDepCond, PrevSIDepCond)) {
952 AdajacentStores.push_back(CurrSI);
955 if (AdajacentStores.size() == 1) {
956 // The outer loop should keep looking from the next store.
960 // Now we have such a group of tainted stores to the same address.
961 DEBUG(dbgs() << "[CompressTaintedStore]\n");
962 DEBUG(dbgs() << "Original BB\n");
963 DEBUG(dbgs() << *BB << '\n');
964 auto* LastSI = AdajacentStores[AdajacentStores.size() - 1];
965 for (unsigned i = 0; i < AdajacentStores.size() - 1; ++i) {
966 auto* SI = AdajacentStores[i];
968 // Use the original address for stores before the last one.
969 SI->setOperand(1, UntaintedAddress);
971 DEBUG(dbgs() << "Store address has been reversed: " << *SI << '\n';);
973 // XXX-comment: Try to make the last store use fewer registers.
974 // If LastSI's storing value is a select based on the condition with which
975 // its address is tainted, transform the tainted address to a select
976 // instruction, as follows:
977 // r1 = Select Cond ? A : B
982 // r1 = Select Cond ? A : B
983 // r2 = Select Cond ? Addr : Addr
985 // The idea is that both Select instructions depend on the same condition,
986 // so hopefully the backend can generate two cmov instructions for them (and
987 // this saves the number of registers needed).
988 auto* LastSIDep = getConditionDependence(LastSI->getPointerOperand());
989 auto* LastSIValue = dyn_cast<Instruction>(LastSI->getValueOperand());
990 if (LastSIValue && LastSIValue->getOpcode() == Instruction::Select &&
991 LastSIValue->getOperand(0) == LastSIDep) {
992 // XXX-comment: Maybe it's better for us to just leave it as an and/or
993 // dependence pattern.
995 IRBuilder<true, NoFolder> Builder(LastSI);
997 Builder.CreateSelect(LastSIDep, UntaintedAddress, UntaintedAddress);
998 LastSI->setOperand(1, Address);
999 DEBUG(dbgs() << "The last store becomes :" << *LastSI << "\n\n";);
1007 bool PassDependenceToStore(Value* OldAddress, StoreInst* NewStore) {
1008 Value* OldDep = getDependence(OldAddress);
1009 // Return false when there's no dependence to pass from the OldAddress.
1014 // No need to pass the dependence to NewStore's address if it already depends
1015 // on whatever 'OldAddress' depends on.
1016 if (StoreAddressDependOnValue(NewStore, OldDep)) {
1019 return taintStoreAddress(NewStore, OldAddress);
1022 SmallSet<Value*, 8> FindDependence(Value* Val) {
1023 SmallSet<Value*, 8> DepSet;
1024 recursivelyFindDependence(&DepSet, Val, true /*Only insert leaf nodes*/);
1028 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal) {
1029 return dependenceSetInclusion(SI->getPointerOperand(), DepVal);
1032 bool StoreDependOnValue(StoreInst* SI, Value* Dep) {
1033 return dependenceSetInclusion(SI, Dep);
1040 bool CodeGenPrepare::runOnFunction(Function &F) {
1041 bool EverMadeChange = false;
1043 if (skipOptnoneFunction(F))
1046 DL = &F.getParent()->getDataLayout();
1048 // Clear per function information.
1049 InsertedInsts.clear();
1050 PromotedInsts.clear();
1054 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
1055 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1056 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1057 OptSize = F.optForSize();
1059 /// This optimization identifies DIV instructions that can be
1060 /// profitably bypassed and carried out with a shorter, faster divide.
1061 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
1062 const DenseMap<unsigned int, unsigned int> &BypassWidths =
1063 TLI->getBypassSlowDivWidths();
1064 BasicBlock* BB = &*F.begin();
1065 while (BB != nullptr) {
1066 // bypassSlowDivision may create new BBs, but we don't want to reapply the
1067 // optimization to those blocks.
1068 BasicBlock* Next = BB->getNextNode();
1069 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
1074 // Eliminate blocks that contain only PHI nodes and an
1075 // unconditional branch.
1076 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
1078 // llvm.dbg.value is far away from the value then iSel may not be able
1079 // handle it properly. iSel will drop llvm.dbg.value if it can not
1080 // find a node corresponding to the value.
1081 EverMadeChange |= placeDbgValues(F);
1083 // If there is a mask, compare against zero, and branch that can be combined
1084 // into a single target instruction, push the mask and compare into branch
1085 // users. Do this before OptimizeBlock -> OptimizeInst ->
1086 // OptimizeCmpExpression, which perturbs the pattern being searched for.
1087 if (!DisableBranchOpts) {
1088 EverMadeChange |= sinkAndCmp(F);
1089 EverMadeChange |= splitBranchCondition(F);
1092 bool MadeChange = true;
1093 while (MadeChange) {
1095 for (Function::iterator I = F.begin(); I != F.end(); ) {
1096 BasicBlock *BB = &*I++;
1097 bool ModifiedDTOnIteration = false;
1098 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
1100 // Restart BB iteration if the dominator tree of the Function was changed
1101 if (ModifiedDTOnIteration)
1104 EverMadeChange |= MadeChange;
1109 if (!DisableBranchOpts) {
1111 SmallPtrSet<BasicBlock*, 8> WorkList;
1112 for (BasicBlock &BB : F) {
1113 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
1114 MadeChange |= ConstantFoldTerminator(&BB, true);
1115 if (!MadeChange) continue;
1117 for (SmallVectorImpl<BasicBlock*>::iterator
1118 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1119 if (pred_begin(*II) == pred_end(*II))
1120 WorkList.insert(*II);
1123 // Delete the dead blocks and any of their dead successors.
1124 MadeChange |= !WorkList.empty();
1125 while (!WorkList.empty()) {
1126 BasicBlock *BB = *WorkList.begin();
1128 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
1130 DeleteDeadBlock(BB);
1132 for (SmallVectorImpl<BasicBlock*>::iterator
1133 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1134 if (pred_begin(*II) == pred_end(*II))
1135 WorkList.insert(*II);
1138 // Merge pairs of basic blocks with unconditional branches, connected by
1140 if (EverMadeChange || MadeChange)
1141 MadeChange |= eliminateFallThrough(F);
1143 EverMadeChange |= MadeChange;
1146 if (!DisableGCOpts) {
1147 SmallVector<Instruction *, 2> Statepoints;
1148 for (BasicBlock &BB : F)
1149 for (Instruction &I : BB)
1150 if (isStatepoint(I))
1151 Statepoints.push_back(&I);
1152 for (auto &I : Statepoints)
1153 EverMadeChange |= simplifyOffsetableRelocate(*I);
1156 // XXX-comment: Delay dealing with relaxed loads in this function to avoid
1157 // further changes done by other passes (e.g., SimplifyCFG).
1158 // Collect all the relaxed loads.
1159 SmallVector<LoadInst*, 1> MonotonicLoadInsts;
1160 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
1161 if (I->isAtomic()) {
1162 switch (I->getOpcode()) {
1163 case Instruction::Load: {
1164 auto* LI = dyn_cast<LoadInst>(&*I);
1165 if (LI->getOrdering() == Monotonic) {
1166 MonotonicLoadInsts.push_back(LI);
1177 AddFakeConditionalBranchAfterMonotonicLoads(MonotonicLoadInsts);
1179 return EverMadeChange;
1182 /// Merge basic blocks which are connected by a single edge, where one of the
1183 /// basic blocks has a single successor pointing to the other basic block,
1184 /// which has a single predecessor.
1185 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
1186 bool Changed = false;
1187 // Scan all of the blocks in the function, except for the entry block.
1188 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1189 BasicBlock *BB = &*I++;
1190 // If the destination block has a single pred, then this is a trivial
1191 // edge, just collapse it.
1192 BasicBlock *SinglePred = BB->getSinglePredecessor();
1194 // Don't merge if BB's address is taken.
1195 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
1197 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
1198 if (Term && !Term->isConditional()) {
1200 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
1201 // Remember if SinglePred was the entry block of the function.
1202 // If so, we will need to move BB back to the entry position.
1203 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1204 MergeBasicBlockIntoOnlyPred(BB, nullptr);
1206 if (isEntry && BB != &BB->getParent()->getEntryBlock())
1207 BB->moveBefore(&BB->getParent()->getEntryBlock());
1209 // We have erased a block. Update the iterator.
1210 I = BB->getIterator();
1216 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
1217 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
1218 /// edges in ways that are non-optimal for isel. Start by eliminating these
1219 /// blocks so we can split them the way we want them.
1220 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
1221 bool MadeChange = false;
1222 // Note that this intentionally skips the entry block.
1223 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1224 BasicBlock *BB = &*I++;
1225 // If this block doesn't end with an uncond branch, ignore it.
1226 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
1227 if (!BI || !BI->isUnconditional())
1230 // If the instruction before the branch (skipping debug info) isn't a phi
1231 // node, then other stuff is happening here.
1232 BasicBlock::iterator BBI = BI->getIterator();
1233 if (BBI != BB->begin()) {
1235 while (isa<DbgInfoIntrinsic>(BBI)) {
1236 if (BBI == BB->begin())
1240 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
1244 // Do not break infinite loops.
1245 BasicBlock *DestBB = BI->getSuccessor(0);
1249 if (!canMergeBlocks(BB, DestBB))
1252 eliminateMostlyEmptyBlock(BB);
1258 /// Return true if we can merge BB into DestBB if there is a single
1259 /// unconditional branch between them, and BB contains no other non-phi
1261 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1262 const BasicBlock *DestBB) const {
1263 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1264 // the successor. If there are more complex condition (e.g. preheaders),
1265 // don't mess around with them.
1266 BasicBlock::const_iterator BBI = BB->begin();
1267 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1268 for (const User *U : PN->users()) {
1269 const Instruction *UI = cast<Instruction>(U);
1270 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1272 // If User is inside DestBB block and it is a PHINode then check
1273 // incoming value. If incoming value is not from BB then this is
1274 // a complex condition (e.g. preheaders) we want to avoid here.
1275 if (UI->getParent() == DestBB) {
1276 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1277 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1278 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1279 if (Insn && Insn->getParent() == BB &&
1280 Insn->getParent() != UPN->getIncomingBlock(I))
1287 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1288 // and DestBB may have conflicting incoming values for the block. If so, we
1289 // can't merge the block.
1290 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1291 if (!DestBBPN) return true; // no conflict.
1293 // Collect the preds of BB.
1294 SmallPtrSet<const BasicBlock*, 16> BBPreds;
1295 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1296 // It is faster to get preds from a PHI than with pred_iterator.
1297 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1298 BBPreds.insert(BBPN->getIncomingBlock(i));
1300 BBPreds.insert(pred_begin(BB), pred_end(BB));
1303 // Walk the preds of DestBB.
1304 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1305 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1306 if (BBPreds.count(Pred)) { // Common predecessor?
1307 BBI = DestBB->begin();
1308 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1309 const Value *V1 = PN->getIncomingValueForBlock(Pred);
1310 const Value *V2 = PN->getIncomingValueForBlock(BB);
1312 // If V2 is a phi node in BB, look up what the mapped value will be.
1313 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1314 if (V2PN->getParent() == BB)
1315 V2 = V2PN->getIncomingValueForBlock(Pred);
1317 // If there is a conflict, bail out.
1318 if (V1 != V2) return false;
1327 /// Eliminate a basic block that has only phi's and an unconditional branch in
1329 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1330 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1331 BasicBlock *DestBB = BI->getSuccessor(0);
1333 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
1335 // If the destination block has a single pred, then this is a trivial edge,
1336 // just collapse it.
1337 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1338 if (SinglePred != DestBB) {
1339 // Remember if SinglePred was the entry block of the function. If so, we
1340 // will need to move BB back to the entry position.
1341 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1342 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
1344 if (isEntry && BB != &BB->getParent()->getEntryBlock())
1345 BB->moveBefore(&BB->getParent()->getEntryBlock());
1347 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1352 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1353 // to handle the new incoming edges it is about to have.
1355 for (BasicBlock::iterator BBI = DestBB->begin();
1356 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1357 // Remove the incoming value for BB, and remember it.
1358 Value *InVal = PN->removeIncomingValue(BB, false);
1360 // Two options: either the InVal is a phi node defined in BB or it is some
1361 // value that dominates BB.
1362 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1363 if (InValPhi && InValPhi->getParent() == BB) {
1364 // Add all of the input values of the input PHI as inputs of this phi.
1365 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1366 PN->addIncoming(InValPhi->getIncomingValue(i),
1367 InValPhi->getIncomingBlock(i));
1369 // Otherwise, add one instance of the dominating value for each edge that
1370 // we will be adding.
1371 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1372 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1373 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
1375 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1376 PN->addIncoming(InVal, *PI);
1381 // The PHIs are now updated, change everything that refers to BB to use
1382 // DestBB and remove BB.
1383 BB->replaceAllUsesWith(DestBB);
1384 BB->eraseFromParent();
1387 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1390 // Computes a map of base pointer relocation instructions to corresponding
1391 // derived pointer relocation instructions given a vector of all relocate calls
1392 static void computeBaseDerivedRelocateMap(
1393 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1394 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1396 // Collect information in two maps: one primarily for locating the base object
1397 // while filling the second map; the second map is the final structure holding
1398 // a mapping between Base and corresponding Derived relocate calls
1399 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1400 for (auto *ThisRelocate : AllRelocateCalls) {
1401 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1402 ThisRelocate->getDerivedPtrIndex());
1403 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1405 for (auto &Item : RelocateIdxMap) {
1406 std::pair<unsigned, unsigned> Key = Item.first;
1407 if (Key.first == Key.second)
1408 // Base relocation: nothing to insert
1411 GCRelocateInst *I = Item.second;
1412 auto BaseKey = std::make_pair(Key.first, Key.first);
1414 // We're iterating over RelocateIdxMap so we cannot modify it.
1415 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1416 if (MaybeBase == RelocateIdxMap.end())
1417 // TODO: We might want to insert a new base object relocate and gep off
1418 // that, if there are enough derived object relocates.
1421 RelocateInstMap[MaybeBase->second].push_back(I);
1425 // Accepts a GEP and extracts the operands into a vector provided they're all
1426 // small integer constants
1427 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1428 SmallVectorImpl<Value *> &OffsetV) {
1429 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1430 // Only accept small constant integer operands
1431 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1432 if (!Op || Op->getZExtValue() > 20)
1436 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1437 OffsetV.push_back(GEP->getOperand(i));
1441 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1442 // replace, computes a replacement, and affects it.
1444 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1445 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1446 bool MadeChange = false;
1447 for (GCRelocateInst *ToReplace : Targets) {
1448 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1449 "Not relocating a derived object of the original base object");
1450 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1451 // A duplicate relocate call. TODO: coalesce duplicates.
1455 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1456 // Base and derived relocates are in different basic blocks.
1457 // In this case transform is only valid when base dominates derived
1458 // relocate. However it would be too expensive to check dominance
1459 // for each such relocate, so we skip the whole transformation.
1463 Value *Base = ToReplace->getBasePtr();
1464 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1465 if (!Derived || Derived->getPointerOperand() != Base)
1468 SmallVector<Value *, 2> OffsetV;
1469 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1472 // Create a Builder and replace the target callsite with a gep
1473 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
1475 // Insert after RelocatedBase
1476 IRBuilder<> Builder(RelocatedBase->getNextNode());
1477 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1479 // If gc_relocate does not match the actual type, cast it to the right type.
1480 // In theory, there must be a bitcast after gc_relocate if the type does not
1481 // match, and we should reuse it to get the derived pointer. But it could be
1485 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1490 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1494 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1495 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1497 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1498 // no matter there is already one or not. In this way, we can handle all cases, and
1499 // the extra bitcast should be optimized away in later passes.
1500 Value *ActualRelocatedBase = RelocatedBase;
1501 if (RelocatedBase->getType() != Base->getType()) {
1502 ActualRelocatedBase =
1503 Builder.CreateBitCast(RelocatedBase, Base->getType());
1505 Value *Replacement = Builder.CreateGEP(
1506 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1507 Replacement->takeName(ToReplace);
1508 // If the newly generated derived pointer's type does not match the original derived
1509 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
1510 Value *ActualReplacement = Replacement;
1511 if (Replacement->getType() != ToReplace->getType()) {
1513 Builder.CreateBitCast(Replacement, ToReplace->getType());
1515 ToReplace->replaceAllUsesWith(ActualReplacement);
1516 ToReplace->eraseFromParent();
1526 // %ptr = gep %base + 15
1527 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1528 // %base' = relocate(%tok, i32 4, i32 4)
1529 // %ptr' = relocate(%tok, i32 4, i32 5)
1530 // %val = load %ptr'
1535 // %ptr = gep %base + 15
1536 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1537 // %base' = gc.relocate(%tok, i32 4, i32 4)
1538 // %ptr' = gep %base' + 15
1539 // %val = load %ptr'
1540 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1541 bool MadeChange = false;
1542 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1544 for (auto *U : I.users())
1545 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1546 // Collect all the relocate calls associated with a statepoint
1547 AllRelocateCalls.push_back(Relocate);
1549 // We need atleast one base pointer relocation + one derived pointer
1550 // relocation to mangle
1551 if (AllRelocateCalls.size() < 2)
1554 // RelocateInstMap is a mapping from the base relocate instruction to the
1555 // corresponding derived relocate instructions
1556 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1557 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1558 if (RelocateInstMap.empty())
1561 for (auto &Item : RelocateInstMap)
1562 // Item.first is the RelocatedBase to offset against
1563 // Item.second is the vector of Targets to replace
1564 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1568 /// SinkCast - Sink the specified cast instruction into its user blocks
1569 static bool SinkCast(CastInst *CI) {
1570 BasicBlock *DefBB = CI->getParent();
1572 /// InsertedCasts - Only insert a cast in each block once.
1573 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1575 bool MadeChange = false;
1576 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1578 Use &TheUse = UI.getUse();
1579 Instruction *User = cast<Instruction>(*UI);
1581 // Figure out which BB this cast is used in. For PHI's this is the
1582 // appropriate predecessor block.
1583 BasicBlock *UserBB = User->getParent();
1584 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1585 UserBB = PN->getIncomingBlock(TheUse);
1588 // Preincrement use iterator so we don't invalidate it.
1591 // If the block selected to receive the cast is an EH pad that does not
1592 // allow non-PHI instructions before the terminator, we can't sink the
1594 if (UserBB->getTerminator()->isEHPad())
1597 // If this user is in the same block as the cast, don't change the cast.
1598 if (UserBB == DefBB) continue;
1600 // If we have already inserted a cast into this block, use it.
1601 CastInst *&InsertedCast = InsertedCasts[UserBB];
1603 if (!InsertedCast) {
1604 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1605 assert(InsertPt != UserBB->end());
1606 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1607 CI->getType(), "", &*InsertPt);
1610 // Replace a use of the cast with a use of the new cast.
1611 TheUse = InsertedCast;
1616 // If we removed all uses, nuke the cast.
1617 if (CI->use_empty()) {
1618 CI->eraseFromParent();
1625 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1626 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1627 /// reduce the number of virtual registers that must be created and coalesced.
1629 /// Return true if any changes are made.
1631 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1632 const DataLayout &DL) {
1633 // If this is a noop copy,
1634 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1635 EVT DstVT = TLI.getValueType(DL, CI->getType());
1637 // This is an fp<->int conversion?
1638 if (SrcVT.isInteger() != DstVT.isInteger())
1641 // If this is an extension, it will be a zero or sign extension, which
1643 if (SrcVT.bitsLT(DstVT)) return false;
1645 // If these values will be promoted, find out what they will be promoted
1646 // to. This helps us consider truncates on PPC as noop copies when they
1648 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1649 TargetLowering::TypePromoteInteger)
1650 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1651 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1652 TargetLowering::TypePromoteInteger)
1653 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1655 // If, after promotion, these are the same types, this is a noop copy.
1659 return SinkCast(CI);
1662 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1665 /// Return true if any changes were made.
1666 static bool CombineUAddWithOverflow(CmpInst *CI) {
1670 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1673 Type *Ty = AddI->getType();
1674 if (!isa<IntegerType>(Ty))
1677 // We don't want to move around uses of condition values this late, so we we
1678 // check if it is legal to create the call to the intrinsic in the basic
1679 // block containing the icmp:
1681 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1685 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1687 if (AddI->hasOneUse())
1688 assert(*AddI->user_begin() == CI && "expected!");
1691 Module *M = CI->getModule();
1692 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1694 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1696 auto *UAddWithOverflow =
1697 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1698 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1700 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1702 CI->replaceAllUsesWith(Overflow);
1703 AddI->replaceAllUsesWith(UAdd);
1704 CI->eraseFromParent();
1705 AddI->eraseFromParent();
1709 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1710 /// registers that must be created and coalesced. This is a clear win except on
1711 /// targets with multiple condition code registers (PowerPC), where it might
1712 /// lose; some adjustment may be wanted there.
1714 /// Return true if any changes are made.
1715 static bool SinkCmpExpression(CmpInst *CI) {
1716 BasicBlock *DefBB = CI->getParent();
1718 /// Only insert a cmp in each block once.
1719 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1721 bool MadeChange = false;
1722 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1724 Use &TheUse = UI.getUse();
1725 Instruction *User = cast<Instruction>(*UI);
1727 // Preincrement use iterator so we don't invalidate it.
1730 // Don't bother for PHI nodes.
1731 if (isa<PHINode>(User))
1734 // Figure out which BB this cmp is used in.
1735 BasicBlock *UserBB = User->getParent();
1737 // If this user is in the same block as the cmp, don't change the cmp.
1738 if (UserBB == DefBB) continue;
1740 // If we have already inserted a cmp into this block, use it.
1741 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1744 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1745 assert(InsertPt != UserBB->end());
1747 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1748 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1751 // Replace a use of the cmp with a use of the new cmp.
1752 TheUse = InsertedCmp;
1757 // If we removed all uses, nuke the cmp.
1758 if (CI->use_empty()) {
1759 CI->eraseFromParent();
1766 static bool OptimizeCmpExpression(CmpInst *CI) {
1767 if (SinkCmpExpression(CI))
1770 if (CombineUAddWithOverflow(CI))
1776 /// Check if the candidates could be combined with a shift instruction, which
1778 /// 1. Truncate instruction
1779 /// 2. And instruction and the imm is a mask of the low bits:
1780 /// imm & (imm+1) == 0
1781 static bool isExtractBitsCandidateUse(Instruction *User) {
1782 if (!isa<TruncInst>(User)) {
1783 if (User->getOpcode() != Instruction::And ||
1784 !isa<ConstantInt>(User->getOperand(1)))
1787 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1789 if ((Cimm & (Cimm + 1)).getBoolValue())
1795 /// Sink both shift and truncate instruction to the use of truncate's BB.
1797 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1798 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1799 const TargetLowering &TLI, const DataLayout &DL) {
1800 BasicBlock *UserBB = User->getParent();
1801 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1802 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1803 bool MadeChange = false;
1805 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1806 TruncE = TruncI->user_end();
1807 TruncUI != TruncE;) {
1809 Use &TruncTheUse = TruncUI.getUse();
1810 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1811 // Preincrement use iterator so we don't invalidate it.
1815 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1819 // If the use is actually a legal node, there will not be an
1820 // implicit truncate.
1821 // FIXME: always querying the result type is just an
1822 // approximation; some nodes' legality is determined by the
1823 // operand or other means. There's no good way to find out though.
1824 if (TLI.isOperationLegalOrCustom(
1825 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1828 // Don't bother for PHI nodes.
1829 if (isa<PHINode>(TruncUser))
1832 BasicBlock *TruncUserBB = TruncUser->getParent();
1834 if (UserBB == TruncUserBB)
1837 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1838 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1840 if (!InsertedShift && !InsertedTrunc) {
1841 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1842 assert(InsertPt != TruncUserBB->end());
1844 if (ShiftI->getOpcode() == Instruction::AShr)
1845 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1848 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1852 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1854 assert(TruncInsertPt != TruncUserBB->end());
1856 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
1857 TruncI->getType(), "", &*TruncInsertPt);
1861 TruncTheUse = InsertedTrunc;
1867 /// Sink the shift *right* instruction into user blocks if the uses could
1868 /// potentially be combined with this shift instruction and generate BitExtract
1869 /// instruction. It will only be applied if the architecture supports BitExtract
1870 /// instruction. Here is an example:
1872 /// %x.extract.shift = lshr i64 %arg1, 32
1874 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1878 /// %x.extract.shift.1 = lshr i64 %arg1, 32
1879 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1881 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1883 /// Return true if any changes are made.
1884 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1885 const TargetLowering &TLI,
1886 const DataLayout &DL) {
1887 BasicBlock *DefBB = ShiftI->getParent();
1889 /// Only insert instructions in each block once.
1890 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1892 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1894 bool MadeChange = false;
1895 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1897 Use &TheUse = UI.getUse();
1898 Instruction *User = cast<Instruction>(*UI);
1899 // Preincrement use iterator so we don't invalidate it.
1902 // Don't bother for PHI nodes.
1903 if (isa<PHINode>(User))
1906 if (!isExtractBitsCandidateUse(User))
1909 BasicBlock *UserBB = User->getParent();
1911 if (UserBB == DefBB) {
1912 // If the shift and truncate instruction are in the same BB. The use of
1913 // the truncate(TruncUse) may still introduce another truncate if not
1914 // legal. In this case, we would like to sink both shift and truncate
1915 // instruction to the BB of TruncUse.
1918 // i64 shift.result = lshr i64 opnd, imm
1919 // trunc.result = trunc shift.result to i16
1922 // ----> We will have an implicit truncate here if the architecture does
1923 // not have i16 compare.
1924 // cmp i16 trunc.result, opnd2
1926 if (isa<TruncInst>(User) && shiftIsLegal
1927 // If the type of the truncate is legal, no trucate will be
1928 // introduced in other basic blocks.
1930 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1932 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1936 // If we have already inserted a shift into this block, use it.
1937 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1939 if (!InsertedShift) {
1940 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1941 assert(InsertPt != UserBB->end());
1943 if (ShiftI->getOpcode() == Instruction::AShr)
1944 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1947 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1953 // Replace a use of the shift with a use of the new shift.
1954 TheUse = InsertedShift;
1957 // If we removed all uses, nuke the shift.
1958 if (ShiftI->use_empty())
1959 ShiftI->eraseFromParent();
1964 // Translate a masked load intrinsic like
1965 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1966 // <16 x i1> %mask, <16 x i32> %passthru)
1967 // to a chain of basic blocks, with loading element one-by-one if
1968 // the appropriate mask bit is set
1970 // %1 = bitcast i8* %addr to i32*
1971 // %2 = extractelement <16 x i1> %mask, i32 0
1972 // %3 = icmp eq i1 %2, true
1973 // br i1 %3, label %cond.load, label %else
1975 //cond.load: ; preds = %0
1976 // %4 = getelementptr i32* %1, i32 0
1977 // %5 = load i32* %4
1978 // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1981 //else: ; preds = %0, %cond.load
1982 // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1983 // %7 = extractelement <16 x i1> %mask, i32 1
1984 // %8 = icmp eq i1 %7, true
1985 // br i1 %8, label %cond.load1, label %else2
1987 //cond.load1: ; preds = %else
1988 // %9 = getelementptr i32* %1, i32 1
1989 // %10 = load i32* %9
1990 // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1993 //else2: ; preds = %else, %cond.load1
1994 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1995 // %12 = extractelement <16 x i1> %mask, i32 2
1996 // %13 = icmp eq i1 %12, true
1997 // br i1 %13, label %cond.load4, label %else5
1999 static void ScalarizeMaskedLoad(CallInst *CI) {
2000 Value *Ptr = CI->getArgOperand(0);
2001 Value *Alignment = CI->getArgOperand(1);
2002 Value *Mask = CI->getArgOperand(2);
2003 Value *Src0 = CI->getArgOperand(3);
2005 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2006 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2007 assert(VecType && "Unexpected return type of masked load intrinsic");
2009 Type *EltTy = CI->getType()->getVectorElementType();
2011 IRBuilder<> Builder(CI->getContext());
2012 Instruction *InsertPt = CI;
2013 BasicBlock *IfBlock = CI->getParent();
2014 BasicBlock *CondBlock = nullptr;
2015 BasicBlock *PrevIfBlock = CI->getParent();
2017 Builder.SetInsertPoint(InsertPt);
2018 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2020 // Short-cut if the mask is all-true.
2021 bool IsAllOnesMask = isa<Constant>(Mask) &&
2022 cast<Constant>(Mask)->isAllOnesValue();
2024 if (IsAllOnesMask) {
2025 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
2026 CI->replaceAllUsesWith(NewI);
2027 CI->eraseFromParent();
2031 // Adjust alignment for the scalar instruction.
2032 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
2033 // Bitcast %addr fron i8* to EltTy*
2035 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2036 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2037 unsigned VectorWidth = VecType->getNumElements();
2039 Value *UndefVal = UndefValue::get(VecType);
2041 // The result vector
2042 Value *VResult = UndefVal;
2044 if (isa<ConstantVector>(Mask)) {
2045 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2046 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2049 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2050 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2051 VResult = Builder.CreateInsertElement(VResult, Load,
2052 Builder.getInt32(Idx));
2054 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2055 CI->replaceAllUsesWith(NewI);
2056 CI->eraseFromParent();
2060 PHINode *Phi = nullptr;
2061 Value *PrevPhi = UndefVal;
2063 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2065 // Fill the "else" block, created in the previous iteration
2067 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2068 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2069 // %to_load = icmp eq i1 %mask_1, true
2070 // br i1 %to_load, label %cond.load, label %else
2073 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2074 Phi->addIncoming(VResult, CondBlock);
2075 Phi->addIncoming(PrevPhi, PrevIfBlock);
2080 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2081 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2082 ConstantInt::get(Predicate->getType(), 1));
2084 // Create "cond" block
2086 // %EltAddr = getelementptr i32* %1, i32 0
2087 // %Elt = load i32* %EltAddr
2088 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2090 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
2091 Builder.SetInsertPoint(InsertPt);
2094 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2095 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2096 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
2098 // Create "else" block, fill it in the next iteration
2099 BasicBlock *NewIfBlock =
2100 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2101 Builder.SetInsertPoint(InsertPt);
2102 Instruction *OldBr = IfBlock->getTerminator();
2103 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2104 OldBr->eraseFromParent();
2105 PrevIfBlock = IfBlock;
2106 IfBlock = NewIfBlock;
2109 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2110 Phi->addIncoming(VResult, CondBlock);
2111 Phi->addIncoming(PrevPhi, PrevIfBlock);
2112 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2113 CI->replaceAllUsesWith(NewI);
2114 CI->eraseFromParent();
2117 // Translate a masked store intrinsic, like
2118 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
2120 // to a chain of basic blocks, that stores element one-by-one if
2121 // the appropriate mask bit is set
2123 // %1 = bitcast i8* %addr to i32*
2124 // %2 = extractelement <16 x i1> %mask, i32 0
2125 // %3 = icmp eq i1 %2, true
2126 // br i1 %3, label %cond.store, label %else
2128 // cond.store: ; preds = %0
2129 // %4 = extractelement <16 x i32> %val, i32 0
2130 // %5 = getelementptr i32* %1, i32 0
2131 // store i32 %4, i32* %5
2134 // else: ; preds = %0, %cond.store
2135 // %6 = extractelement <16 x i1> %mask, i32 1
2136 // %7 = icmp eq i1 %6, true
2137 // br i1 %7, label %cond.store1, label %else2
2139 // cond.store1: ; preds = %else
2140 // %8 = extractelement <16 x i32> %val, i32 1
2141 // %9 = getelementptr i32* %1, i32 1
2142 // store i32 %8, i32* %9
2145 static void ScalarizeMaskedStore(CallInst *CI) {
2146 Value *Src = CI->getArgOperand(0);
2147 Value *Ptr = CI->getArgOperand(1);
2148 Value *Alignment = CI->getArgOperand(2);
2149 Value *Mask = CI->getArgOperand(3);
2151 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2152 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
2153 assert(VecType && "Unexpected data type in masked store intrinsic");
2155 Type *EltTy = VecType->getElementType();
2157 IRBuilder<> Builder(CI->getContext());
2158 Instruction *InsertPt = CI;
2159 BasicBlock *IfBlock = CI->getParent();
2160 Builder.SetInsertPoint(InsertPt);
2161 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2163 // Short-cut if the mask is all-true.
2164 bool IsAllOnesMask = isa<Constant>(Mask) &&
2165 cast<Constant>(Mask)->isAllOnesValue();
2167 if (IsAllOnesMask) {
2168 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
2169 CI->eraseFromParent();
2173 // Adjust alignment for the scalar instruction.
2174 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
2175 // Bitcast %addr fron i8* to EltTy*
2177 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2178 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2179 unsigned VectorWidth = VecType->getNumElements();
2181 if (isa<ConstantVector>(Mask)) {
2182 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2183 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2185 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2187 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2188 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2190 CI->eraseFromParent();
2194 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2196 // Fill the "else" block, created in the previous iteration
2198 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2199 // %to_store = icmp eq i1 %mask_1, true
2200 // br i1 %to_store, label %cond.store, label %else
2202 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2203 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2204 ConstantInt::get(Predicate->getType(), 1));
2206 // Create "cond" block
2208 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
2209 // %EltAddr = getelementptr i32* %1, i32 0
2210 // %store i32 %OneElt, i32* %EltAddr
2212 BasicBlock *CondBlock =
2213 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
2214 Builder.SetInsertPoint(InsertPt);
2216 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2218 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2219 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2221 // Create "else" block, fill it in the next iteration
2222 BasicBlock *NewIfBlock =
2223 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2224 Builder.SetInsertPoint(InsertPt);
2225 Instruction *OldBr = IfBlock->getTerminator();
2226 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2227 OldBr->eraseFromParent();
2228 IfBlock = NewIfBlock;
2230 CI->eraseFromParent();
2233 // Translate a masked gather intrinsic like
2234 // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
2235 // <16 x i1> %Mask, <16 x i32> %Src)
2236 // to a chain of basic blocks, with loading element one-by-one if
2237 // the appropriate mask bit is set
2239 // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
2240 // % Mask0 = extractelement <16 x i1> %Mask, i32 0
2241 // % ToLoad0 = icmp eq i1 % Mask0, true
2242 // br i1 % ToLoad0, label %cond.load, label %else
2245 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2246 // % Load0 = load i32, i32* % Ptr0, align 4
2247 // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
2251 // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
2252 // % Mask1 = extractelement <16 x i1> %Mask, i32 1
2253 // % ToLoad1 = icmp eq i1 % Mask1, true
2254 // br i1 % ToLoad1, label %cond.load1, label %else2
2257 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2258 // % Load1 = load i32, i32* % Ptr1, align 4
2259 // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
2262 // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
2263 // ret <16 x i32> %Result
2264 static void ScalarizeMaskedGather(CallInst *CI) {
2265 Value *Ptrs = CI->getArgOperand(0);
2266 Value *Alignment = CI->getArgOperand(1);
2267 Value *Mask = CI->getArgOperand(2);
2268 Value *Src0 = CI->getArgOperand(3);
2270 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2272 assert(VecType && "Unexpected return type of masked load intrinsic");
2274 IRBuilder<> Builder(CI->getContext());
2275 Instruction *InsertPt = CI;
2276 BasicBlock *IfBlock = CI->getParent();
2277 BasicBlock *CondBlock = nullptr;
2278 BasicBlock *PrevIfBlock = CI->getParent();
2279 Builder.SetInsertPoint(InsertPt);
2280 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2282 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2284 Value *UndefVal = UndefValue::get(VecType);
2286 // The result vector
2287 Value *VResult = UndefVal;
2288 unsigned VectorWidth = VecType->getNumElements();
2290 // Shorten the way if the mask is a vector of constants.
2291 bool IsConstMask = isa<ConstantVector>(Mask);
2294 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2295 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2297 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2298 "Ptr" + Twine(Idx));
2299 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2300 "Load" + Twine(Idx));
2301 VResult = Builder.CreateInsertElement(VResult, Load,
2302 Builder.getInt32(Idx),
2303 "Res" + Twine(Idx));
2305 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2306 CI->replaceAllUsesWith(NewI);
2307 CI->eraseFromParent();
2311 PHINode *Phi = nullptr;
2312 Value *PrevPhi = UndefVal;
2314 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2316 // Fill the "else" block, created in the previous iteration
2318 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
2319 // %ToLoad1 = icmp eq i1 %Mask1, true
2320 // br i1 %ToLoad1, label %cond.load, label %else
2323 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2324 Phi->addIncoming(VResult, CondBlock);
2325 Phi->addIncoming(PrevPhi, PrevIfBlock);
2330 Value *Predicate = Builder.CreateExtractElement(Mask,
2331 Builder.getInt32(Idx),
2332 "Mask" + Twine(Idx));
2333 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2334 ConstantInt::get(Predicate->getType(), 1),
2335 "ToLoad" + Twine(Idx));
2337 // Create "cond" block
2339 // %EltAddr = getelementptr i32* %1, i32 0
2340 // %Elt = load i32* %EltAddr
2341 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2343 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
2344 Builder.SetInsertPoint(InsertPt);
2346 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2347 "Ptr" + Twine(Idx));
2348 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2349 "Load" + Twine(Idx));
2350 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
2351 "Res" + Twine(Idx));
2353 // Create "else" block, fill it in the next iteration
2354 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2355 Builder.SetInsertPoint(InsertPt);
2356 Instruction *OldBr = IfBlock->getTerminator();
2357 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2358 OldBr->eraseFromParent();
2359 PrevIfBlock = IfBlock;
2360 IfBlock = NewIfBlock;
2363 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2364 Phi->addIncoming(VResult, CondBlock);
2365 Phi->addIncoming(PrevPhi, PrevIfBlock);
2366 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2367 CI->replaceAllUsesWith(NewI);
2368 CI->eraseFromParent();
2371 // Translate a masked scatter intrinsic, like
2372 // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
2374 // to a chain of basic blocks, that stores element one-by-one if
2375 // the appropriate mask bit is set.
2377 // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
2378 // % Mask0 = extractelement <16 x i1> % Mask, i32 0
2379 // % ToStore0 = icmp eq i1 % Mask0, true
2380 // br i1 %ToStore0, label %cond.store, label %else
2383 // % Elt0 = extractelement <16 x i32> %Src, i32 0
2384 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2385 // store i32 %Elt0, i32* % Ptr0, align 4
2389 // % Mask1 = extractelement <16 x i1> % Mask, i32 1
2390 // % ToStore1 = icmp eq i1 % Mask1, true
2391 // br i1 % ToStore1, label %cond.store1, label %else2
2394 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2395 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2396 // store i32 % Elt1, i32* % Ptr1, align 4
2399 static void ScalarizeMaskedScatter(CallInst *CI) {
2400 Value *Src = CI->getArgOperand(0);
2401 Value *Ptrs = CI->getArgOperand(1);
2402 Value *Alignment = CI->getArgOperand(2);
2403 Value *Mask = CI->getArgOperand(3);
2405 assert(isa<VectorType>(Src->getType()) &&
2406 "Unexpected data type in masked scatter intrinsic");
2407 assert(isa<VectorType>(Ptrs->getType()) &&
2408 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
2409 "Vector of pointers is expected in masked scatter intrinsic");
2411 IRBuilder<> Builder(CI->getContext());
2412 Instruction *InsertPt = CI;
2413 BasicBlock *IfBlock = CI->getParent();
2414 Builder.SetInsertPoint(InsertPt);
2415 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2417 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2418 unsigned VectorWidth = Src->getType()->getVectorNumElements();
2420 // Shorten the way if the mask is a vector of constants.
2421 bool IsConstMask = isa<ConstantVector>(Mask);
2424 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2425 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2427 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2428 "Elt" + Twine(Idx));
2429 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2430 "Ptr" + Twine(Idx));
2431 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2433 CI->eraseFromParent();
2436 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2437 // Fill the "else" block, created in the previous iteration
2439 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
2440 // % ToStore = icmp eq i1 % Mask1, true
2441 // br i1 % ToStore, label %cond.store, label %else
2443 Value *Predicate = Builder.CreateExtractElement(Mask,
2444 Builder.getInt32(Idx),
2445 "Mask" + Twine(Idx));
2447 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2448 ConstantInt::get(Predicate->getType(), 1),
2449 "ToStore" + Twine(Idx));
2451 // Create "cond" block
2453 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2454 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2455 // %store i32 % Elt1, i32* % Ptr1
2457 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2458 Builder.SetInsertPoint(InsertPt);
2460 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2461 "Elt" + Twine(Idx));
2462 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2463 "Ptr" + Twine(Idx));
2464 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2466 // Create "else" block, fill it in the next iteration
2467 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2468 Builder.SetInsertPoint(InsertPt);
2469 Instruction *OldBr = IfBlock->getTerminator();
2470 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2471 OldBr->eraseFromParent();
2472 IfBlock = NewIfBlock;
2474 CI->eraseFromParent();
2477 /// If counting leading or trailing zeros is an expensive operation and a zero
2478 /// input is defined, add a check for zero to avoid calling the intrinsic.
2480 /// We want to transform:
2481 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2485 /// %cmpz = icmp eq i64 %A, 0
2486 /// br i1 %cmpz, label %cond.end, label %cond.false
2488 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2489 /// br label %cond.end
2491 /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2493 /// If the transform is performed, return true and set ModifiedDT to true.
2494 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2495 const TargetLowering *TLI,
2496 const DataLayout *DL,
2501 // If a zero input is undefined, it doesn't make sense to despeculate that.
2502 if (match(CountZeros->getOperand(1), m_One()))
2505 // If it's cheap to speculate, there's nothing to do.
2506 auto IntrinsicID = CountZeros->getIntrinsicID();
2507 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2508 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2511 // Only handle legal scalar cases. Anything else requires too much work.
2512 Type *Ty = CountZeros->getType();
2513 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
2514 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
2517 // The intrinsic will be sunk behind a compare against zero and branch.
2518 BasicBlock *StartBlock = CountZeros->getParent();
2519 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2521 // Create another block after the count zero intrinsic. A PHI will be added
2522 // in this block to select the result of the intrinsic or the bit-width
2523 // constant if the input to the intrinsic is zero.
2524 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2525 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2527 // Set up a builder to create a compare, conditional branch, and PHI.
2528 IRBuilder<> Builder(CountZeros->getContext());
2529 Builder.SetInsertPoint(StartBlock->getTerminator());
2530 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2532 // Replace the unconditional branch that was created by the first split with
2533 // a compare against zero and a conditional branch.
2534 Value *Zero = Constant::getNullValue(Ty);
2535 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2536 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2537 StartBlock->getTerminator()->eraseFromParent();
2539 // Create a PHI in the end block to select either the output of the intrinsic
2540 // or the bit width of the operand.
2541 Builder.SetInsertPoint(&EndBlock->front());
2542 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2543 CountZeros->replaceAllUsesWith(PN);
2544 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2545 PN->addIncoming(BitWidth, StartBlock);
2546 PN->addIncoming(CountZeros, CallBlock);
2548 // We are explicitly handling the zero case, so we can set the intrinsic's
2549 // undefined zero argument to 'true'. This will also prevent reprocessing the
2550 // intrinsic; we only despeculate when a zero input is defined.
2551 CountZeros->setArgOperand(1, Builder.getTrue());
2556 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
2557 BasicBlock *BB = CI->getParent();
2559 // Lower inline assembly if we can.
2560 // If we found an inline asm expession, and if the target knows how to
2561 // lower it to normal LLVM code, do so now.
2562 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2563 if (TLI->ExpandInlineAsm(CI)) {
2564 // Avoid invalidating the iterator.
2565 CurInstIterator = BB->begin();
2566 // Avoid processing instructions out of order, which could cause
2567 // reuse before a value is defined.
2571 // Sink address computing for memory operands into the block.
2572 if (optimizeInlineAsmInst(CI))
2576 // Align the pointer arguments to this call if the target thinks it's a good
2578 unsigned MinSize, PrefAlign;
2579 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2580 for (auto &Arg : CI->arg_operands()) {
2581 // We want to align both objects whose address is used directly and
2582 // objects whose address is used in casts and GEPs, though it only makes
2583 // sense for GEPs if the offset is a multiple of the desired alignment and
2584 // if size - offset meets the size threshold.
2585 if (!Arg->getType()->isPointerTy())
2587 APInt Offset(DL->getPointerSizeInBits(
2588 cast<PointerType>(Arg->getType())->getAddressSpace()),
2590 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2591 uint64_t Offset2 = Offset.getLimitedValue();
2592 if ((Offset2 & (PrefAlign-1)) != 0)
2595 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2596 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2597 AI->setAlignment(PrefAlign);
2598 // Global variables can only be aligned if they are defined in this
2599 // object (i.e. they are uniquely initialized in this object), and
2600 // over-aligning global variables that have an explicit section is
2603 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2604 GV->getAlignment() < PrefAlign &&
2605 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
2607 GV->setAlignment(PrefAlign);
2609 // If this is a memcpy (or similar) then we may be able to improve the
2611 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2612 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2613 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2614 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2615 if (Align > MI->getAlignment())
2616 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2620 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2622 switch (II->getIntrinsicID()) {
2624 case Intrinsic::objectsize: {
2625 // Lower all uses of llvm.objectsize.*
2626 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
2627 Type *ReturnTy = CI->getType();
2628 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
2630 // Substituting this can cause recursive simplifications, which can
2631 // invalidate our iterator. Use a WeakVH to hold onto it in case this
2633 WeakVH IterHandle(&*CurInstIterator);
2635 replaceAndRecursivelySimplify(CI, RetVal,
2638 // If the iterator instruction was recursively deleted, start over at the
2639 // start of the block.
2640 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
2641 CurInstIterator = BB->begin();
2646 case Intrinsic::masked_load: {
2647 // Scalarize unsupported vector masked load
2648 if (!TTI->isLegalMaskedLoad(CI->getType())) {
2649 ScalarizeMaskedLoad(CI);
2655 case Intrinsic::masked_store: {
2656 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
2657 ScalarizeMaskedStore(CI);
2663 case Intrinsic::masked_gather: {
2664 if (!TTI->isLegalMaskedGather(CI->getType())) {
2665 ScalarizeMaskedGather(CI);
2671 case Intrinsic::masked_scatter: {
2672 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
2673 ScalarizeMaskedScatter(CI);
2679 case Intrinsic::aarch64_stlxr:
2680 case Intrinsic::aarch64_stxr: {
2681 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2682 if (!ExtVal || !ExtVal->hasOneUse() ||
2683 ExtVal->getParent() == CI->getParent())
2685 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2686 ExtVal->moveBefore(CI);
2687 // Mark this instruction as "inserted by CGP", so that other
2688 // optimizations don't touch it.
2689 InsertedInsts.insert(ExtVal);
2692 case Intrinsic::invariant_group_barrier:
2693 II->replaceAllUsesWith(II->getArgOperand(0));
2694 II->eraseFromParent();
2697 case Intrinsic::cttz:
2698 case Intrinsic::ctlz:
2699 // If counting zeros is expensive, try to avoid it.
2700 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2704 // Unknown address space.
2705 // TODO: Target hook to pick which address space the intrinsic cares
2707 unsigned AddrSpace = ~0u;
2708 SmallVector<Value*, 2> PtrOps;
2710 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
2711 while (!PtrOps.empty())
2712 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
2717 // From here on out we're working with named functions.
2718 if (!CI->getCalledFunction()) return false;
2720 // Lower all default uses of _chk calls. This is very similar
2721 // to what InstCombineCalls does, but here we are only lowering calls
2722 // to fortified library functions (e.g. __memcpy_chk) that have the default
2723 // "don't know" as the objectsize. Anything else should be left alone.
2724 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2725 if (Value *V = Simplifier.optimizeCall(CI)) {
2726 CI->replaceAllUsesWith(V);
2727 CI->eraseFromParent();
2733 /// Look for opportunities to duplicate return instructions to the predecessor
2734 /// to enable tail call optimizations. The case it is currently looking for is:
2737 /// %tmp0 = tail call i32 @f0()
2738 /// br label %return
2740 /// %tmp1 = tail call i32 @f1()
2741 /// br label %return
2743 /// %tmp2 = tail call i32 @f2()
2744 /// br label %return
2746 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2754 /// %tmp0 = tail call i32 @f0()
2757 /// %tmp1 = tail call i32 @f1()
2760 /// %tmp2 = tail call i32 @f2()
2763 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
2767 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
2771 PHINode *PN = nullptr;
2772 BitCastInst *BCI = nullptr;
2773 Value *V = RI->getReturnValue();
2775 BCI = dyn_cast<BitCastInst>(V);
2777 V = BCI->getOperand(0);
2779 PN = dyn_cast<PHINode>(V);
2784 if (PN && PN->getParent() != BB)
2787 // It's not safe to eliminate the sign / zero extension of the return value.
2788 // See llvm::isInTailCallPosition().
2789 const Function *F = BB->getParent();
2790 AttributeSet CallerAttrs = F->getAttributes();
2791 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
2792 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
2795 // Make sure there are no instructions between the PHI and return, or that the
2796 // return is the first instruction in the block.
2798 BasicBlock::iterator BI = BB->begin();
2799 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
2801 // Also skip over the bitcast.
2806 BasicBlock::iterator BI = BB->begin();
2807 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2812 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2814 SmallVector<CallInst*, 4> TailCalls;
2816 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2817 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2818 // Make sure the phi value is indeed produced by the tail call.
2819 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2820 TLI->mayBeEmittedAsTailCall(CI))
2821 TailCalls.push_back(CI);
2824 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
2825 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
2826 if (!VisitedBBs.insert(*PI).second)
2829 BasicBlock::InstListType &InstList = (*PI)->getInstList();
2830 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2831 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
2832 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2836 CallInst *CI = dyn_cast<CallInst>(&*RI);
2837 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
2838 TailCalls.push_back(CI);
2842 bool Changed = false;
2843 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2844 CallInst *CI = TailCalls[i];
2847 // Conservatively require the attributes of the call to match those of the
2848 // return. Ignore noalias because it doesn't affect the call sequence.
2849 AttributeSet CalleeAttrs = CS.getAttributes();
2850 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
2851 removeAttribute(Attribute::NoAlias) !=
2852 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
2853 removeAttribute(Attribute::NoAlias))
2856 // Make sure the call instruction is followed by an unconditional branch to
2857 // the return block.
2858 BasicBlock *CallBB = CI->getParent();
2859 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2860 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2863 // Duplicate the return into CallBB.
2864 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
2865 ModifiedDT = Changed = true;
2869 // If we eliminated all predecessors of the block, delete the block now.
2870 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
2871 BB->eraseFromParent();
2876 //===----------------------------------------------------------------------===//
2877 // Memory Optimization
2878 //===----------------------------------------------------------------------===//
2882 /// This is an extended version of TargetLowering::AddrMode
2883 /// which holds actual Value*'s for register values.
2884 struct ExtAddrMode : public TargetLowering::AddrMode {
2887 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
2888 void print(raw_ostream &OS) const;
2891 bool operator==(const ExtAddrMode& O) const {
2892 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2893 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2894 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2899 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2905 void ExtAddrMode::print(raw_ostream &OS) const {
2906 bool NeedPlus = false;
2909 OS << (NeedPlus ? " + " : "")
2911 BaseGV->printAsOperand(OS, /*PrintType=*/false);
2916 OS << (NeedPlus ? " + " : "")
2922 OS << (NeedPlus ? " + " : "")
2924 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2928 OS << (NeedPlus ? " + " : "")
2930 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2936 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2937 void ExtAddrMode::dump() const {
2943 /// \brief This class provides transaction based operation on the IR.
2944 /// Every change made through this class is recorded in the internal state and
2945 /// can be undone (rollback) until commit is called.
2946 class TypePromotionTransaction {
2948 /// \brief This represents the common interface of the individual transaction.
2949 /// Each class implements the logic for doing one specific modification on
2950 /// the IR via the TypePromotionTransaction.
2951 class TypePromotionAction {
2953 /// The Instruction modified.
2957 /// \brief Constructor of the action.
2958 /// The constructor performs the related action on the IR.
2959 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2961 virtual ~TypePromotionAction() {}
2963 /// \brief Undo the modification done by this action.
2964 /// When this method is called, the IR must be in the same state as it was
2965 /// before this action was applied.
2966 /// \pre Undoing the action works if and only if the IR is in the exact same
2967 /// state as it was directly after this action was applied.
2968 virtual void undo() = 0;
2970 /// \brief Advocate every change made by this action.
2971 /// When the results on the IR of the action are to be kept, it is important
2972 /// to call this function, otherwise hidden information may be kept forever.
2973 virtual void commit() {
2974 // Nothing to be done, this action is not doing anything.
2978 /// \brief Utility to remember the position of an instruction.
2979 class InsertionHandler {
2980 /// Position of an instruction.
2981 /// Either an instruction:
2982 /// - Is the first in a basic block: BB is used.
2983 /// - Has a previous instructon: PrevInst is used.
2985 Instruction *PrevInst;
2988 /// Remember whether or not the instruction had a previous instruction.
2989 bool HasPrevInstruction;
2992 /// \brief Record the position of \p Inst.
2993 InsertionHandler(Instruction *Inst) {
2994 BasicBlock::iterator It = Inst->getIterator();
2995 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2996 if (HasPrevInstruction)
2997 Point.PrevInst = &*--It;
2999 Point.BB = Inst->getParent();
3002 /// \brief Insert \p Inst at the recorded position.
3003 void insert(Instruction *Inst) {
3004 if (HasPrevInstruction) {
3005 if (Inst->getParent())
3006 Inst->removeFromParent();
3007 Inst->insertAfter(Point.PrevInst);
3009 Instruction *Position = &*Point.BB->getFirstInsertionPt();
3010 if (Inst->getParent())
3011 Inst->moveBefore(Position);
3013 Inst->insertBefore(Position);
3018 /// \brief Move an instruction before another.
3019 class InstructionMoveBefore : public TypePromotionAction {
3020 /// Original position of the instruction.
3021 InsertionHandler Position;
3024 /// \brief Move \p Inst before \p Before.
3025 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
3026 : TypePromotionAction(Inst), Position(Inst) {
3027 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
3028 Inst->moveBefore(Before);
3031 /// \brief Move the instruction back to its original position.
3032 void undo() override {
3033 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3034 Position.insert(Inst);
3038 /// \brief Set the operand of an instruction with a new value.
3039 class OperandSetter : public TypePromotionAction {
3040 /// Original operand of the instruction.
3042 /// Index of the modified instruction.
3046 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
3047 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3048 : TypePromotionAction(Inst), Idx(Idx) {
3049 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3050 << "for:" << *Inst << "\n"
3051 << "with:" << *NewVal << "\n");
3052 Origin = Inst->getOperand(Idx);
3053 Inst->setOperand(Idx, NewVal);
3056 /// \brief Restore the original value of the instruction.
3057 void undo() override {
3058 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3059 << "for: " << *Inst << "\n"
3060 << "with: " << *Origin << "\n");
3061 Inst->setOperand(Idx, Origin);
3065 /// \brief Hide the operands of an instruction.
3066 /// Do as if this instruction was not using any of its operands.
3067 class OperandsHider : public TypePromotionAction {
3068 /// The list of original operands.
3069 SmallVector<Value *, 4> OriginalValues;
3072 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
3073 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3074 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3075 unsigned NumOpnds = Inst->getNumOperands();
3076 OriginalValues.reserve(NumOpnds);
3077 for (unsigned It = 0; It < NumOpnds; ++It) {
3078 // Save the current operand.
3079 Value *Val = Inst->getOperand(It);
3080 OriginalValues.push_back(Val);
3082 // We could use OperandSetter here, but that would imply an overhead
3083 // that we are not willing to pay.
3084 Inst->setOperand(It, UndefValue::get(Val->getType()));
3088 /// \brief Restore the original list of uses.
3089 void undo() override {
3090 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3091 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3092 Inst->setOperand(It, OriginalValues[It]);
3096 /// \brief Build a truncate instruction.
3097 class TruncBuilder : public TypePromotionAction {
3100 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
3102 /// trunc Opnd to Ty.
3103 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3104 IRBuilder<> Builder(Opnd);
3105 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3106 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3109 /// \brief Get the built value.
3110 Value *getBuiltValue() { return Val; }
3112 /// \brief Remove the built instruction.
3113 void undo() override {
3114 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3115 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3116 IVal->eraseFromParent();
3120 /// \brief Build a sign extension instruction.
3121 class SExtBuilder : public TypePromotionAction {
3124 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
3126 /// sext Opnd to Ty.
3127 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3128 : TypePromotionAction(InsertPt) {
3129 IRBuilder<> Builder(InsertPt);
3130 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3131 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3134 /// \brief Get the built value.
3135 Value *getBuiltValue() { return Val; }
3137 /// \brief Remove the built instruction.
3138 void undo() override {
3139 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3140 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3141 IVal->eraseFromParent();
3145 /// \brief Build a zero extension instruction.
3146 class ZExtBuilder : public TypePromotionAction {
3149 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
3151 /// zext Opnd to Ty.
3152 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3153 : TypePromotionAction(InsertPt) {
3154 IRBuilder<> Builder(InsertPt);
3155 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3156 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3159 /// \brief Get the built value.
3160 Value *getBuiltValue() { return Val; }
3162 /// \brief Remove the built instruction.
3163 void undo() override {
3164 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3165 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3166 IVal->eraseFromParent();
3170 /// \brief Mutate an instruction to another type.
3171 class TypeMutator : public TypePromotionAction {
3172 /// Record the original type.
3176 /// \brief Mutate the type of \p Inst into \p NewTy.
3177 TypeMutator(Instruction *Inst, Type *NewTy)
3178 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3179 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3181 Inst->mutateType(NewTy);
3184 /// \brief Mutate the instruction back to its original type.
3185 void undo() override {
3186 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3188 Inst->mutateType(OrigTy);
3192 /// \brief Replace the uses of an instruction by another instruction.
3193 class UsesReplacer : public TypePromotionAction {
3194 /// Helper structure to keep track of the replaced uses.
3195 struct InstructionAndIdx {
3196 /// The instruction using the instruction.
3198 /// The index where this instruction is used for Inst.
3200 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3201 : Inst(Inst), Idx(Idx) {}
3204 /// Keep track of the original uses (pair Instruction, Index).
3205 SmallVector<InstructionAndIdx, 4> OriginalUses;
3206 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
3209 /// \brief Replace all the use of \p Inst by \p New.
3210 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
3211 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3213 // Record the original uses.
3214 for (Use &U : Inst->uses()) {
3215 Instruction *UserI = cast<Instruction>(U.getUser());
3216 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3218 // Now, we can replace the uses.
3219 Inst->replaceAllUsesWith(New);
3222 /// \brief Reassign the original uses of Inst to Inst.
3223 void undo() override {
3224 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3225 for (use_iterator UseIt = OriginalUses.begin(),
3226 EndIt = OriginalUses.end();
3227 UseIt != EndIt; ++UseIt) {
3228 UseIt->Inst->setOperand(UseIt->Idx, Inst);
3233 /// \brief Remove an instruction from the IR.
3234 class InstructionRemover : public TypePromotionAction {
3235 /// Original position of the instruction.
3236 InsertionHandler Inserter;
3237 /// Helper structure to hide all the link to the instruction. In other
3238 /// words, this helps to do as if the instruction was removed.
3239 OperandsHider Hider;
3240 /// Keep track of the uses replaced, if any.
3241 UsesReplacer *Replacer;
3244 /// \brief Remove all reference of \p Inst and optinally replace all its
3246 /// \pre If !Inst->use_empty(), then New != nullptr
3247 InstructionRemover(Instruction *Inst, Value *New = nullptr)
3248 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3251 Replacer = new UsesReplacer(Inst, New);
3252 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3253 Inst->removeFromParent();
3256 ~InstructionRemover() override { delete Replacer; }
3258 /// \brief Really remove the instruction.
3259 void commit() override { delete Inst; }
3261 /// \brief Resurrect the instruction and reassign it to the proper uses if
3262 /// new value was provided when build this action.
3263 void undo() override {
3264 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3265 Inserter.insert(Inst);
3273 /// Restoration point.
3274 /// The restoration point is a pointer to an action instead of an iterator
3275 /// because the iterator may be invalidated but not the pointer.
3276 typedef const TypePromotionAction *ConstRestorationPt;
3277 /// Advocate every changes made in that transaction.
3279 /// Undo all the changes made after the given point.
3280 void rollback(ConstRestorationPt Point);
3281 /// Get the current restoration point.
3282 ConstRestorationPt getRestorationPoint() const;
3284 /// \name API for IR modification with state keeping to support rollback.
3286 /// Same as Instruction::setOperand.
3287 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3288 /// Same as Instruction::eraseFromParent.
3289 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3290 /// Same as Value::replaceAllUsesWith.
3291 void replaceAllUsesWith(Instruction *Inst, Value *New);
3292 /// Same as Value::mutateType.
3293 void mutateType(Instruction *Inst, Type *NewTy);
3294 /// Same as IRBuilder::createTrunc.
3295 Value *createTrunc(Instruction *Opnd, Type *Ty);
3296 /// Same as IRBuilder::createSExt.
3297 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3298 /// Same as IRBuilder::createZExt.
3299 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3300 /// Same as Instruction::moveBefore.
3301 void moveBefore(Instruction *Inst, Instruction *Before);
3305 /// The ordered list of actions made so far.
3306 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3307 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
3310 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3313 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
3316 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3319 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
3322 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3324 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3327 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3328 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3331 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3333 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3334 Value *Val = Ptr->getBuiltValue();
3335 Actions.push_back(std::move(Ptr));
3339 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3340 Value *Opnd, Type *Ty) {
3341 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3342 Value *Val = Ptr->getBuiltValue();
3343 Actions.push_back(std::move(Ptr));
3347 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3348 Value *Opnd, Type *Ty) {
3349 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3350 Value *Val = Ptr->getBuiltValue();
3351 Actions.push_back(std::move(Ptr));
3355 void TypePromotionTransaction::moveBefore(Instruction *Inst,
3356 Instruction *Before) {
3358 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
3361 TypePromotionTransaction::ConstRestorationPt
3362 TypePromotionTransaction::getRestorationPoint() const {
3363 return !Actions.empty() ? Actions.back().get() : nullptr;
3366 void TypePromotionTransaction::commit() {
3367 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
3373 void TypePromotionTransaction::rollback(
3374 TypePromotionTransaction::ConstRestorationPt Point) {
3375 while (!Actions.empty() && Point != Actions.back().get()) {
3376 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3381 /// \brief A helper class for matching addressing modes.
3383 /// This encapsulates the logic for matching the target-legal addressing modes.
3384 class AddressingModeMatcher {
3385 SmallVectorImpl<Instruction*> &AddrModeInsts;
3386 const TargetMachine &TM;
3387 const TargetLowering &TLI;
3388 const DataLayout &DL;
3390 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3391 /// the memory instruction that we're computing this address for.
3394 Instruction *MemoryInst;
3396 /// This is the addressing mode that we're building up. This is
3397 /// part of the return value of this addressing mode matching stuff.
3398 ExtAddrMode &AddrMode;
3400 /// The instructions inserted by other CodeGenPrepare optimizations.
3401 const SetOfInstrs &InsertedInsts;
3402 /// A map from the instructions to their type before promotion.
3403 InstrToOrigTy &PromotedInsts;
3404 /// The ongoing transaction where every action should be registered.
3405 TypePromotionTransaction &TPT;
3407 /// This is set to true when we should not do profitability checks.
3408 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3409 bool IgnoreProfitability;
3411 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
3412 const TargetMachine &TM, Type *AT, unsigned AS,
3413 Instruction *MI, ExtAddrMode &AM,
3414 const SetOfInstrs &InsertedInsts,
3415 InstrToOrigTy &PromotedInsts,
3416 TypePromotionTransaction &TPT)
3417 : AddrModeInsts(AMI), TM(TM),
3418 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
3419 ->getTargetLowering()),
3420 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3421 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3422 PromotedInsts(PromotedInsts), TPT(TPT) {
3423 IgnoreProfitability = false;
3427 /// Find the maximal addressing mode that a load/store of V can fold,
3428 /// give an access type of AccessTy. This returns a list of involved
3429 /// instructions in AddrModeInsts.
3430 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3432 /// \p PromotedInsts maps the instructions to their type before promotion.
3433 /// \p The ongoing transaction where every action should be registered.
3434 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
3435 Instruction *MemoryInst,
3436 SmallVectorImpl<Instruction*> &AddrModeInsts,
3437 const TargetMachine &TM,
3438 const SetOfInstrs &InsertedInsts,
3439 InstrToOrigTy &PromotedInsts,
3440 TypePromotionTransaction &TPT) {
3443 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
3444 MemoryInst, Result, InsertedInsts,
3445 PromotedInsts, TPT).matchAddr(V, 0);
3446 (void)Success; assert(Success && "Couldn't select *anything*?");
3450 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3451 bool matchAddr(Value *V, unsigned Depth);
3452 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
3453 bool *MovedAway = nullptr);
3454 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3455 ExtAddrMode &AMBefore,
3456 ExtAddrMode &AMAfter);
3457 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3458 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3459 Value *PromotedOperand) const;
3462 /// Try adding ScaleReg*Scale to the current addressing mode.
3463 /// Return true and update AddrMode if this addr mode is legal for the target,
3465 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3467 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3468 // mode. Just process that directly.
3470 return matchAddr(ScaleReg, Depth);
3472 // If the scale is 0, it takes nothing to add this.
3476 // If we already have a scale of this value, we can add to it, otherwise, we
3477 // need an available scale field.
3478 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3481 ExtAddrMode TestAddrMode = AddrMode;
3483 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3484 // [A+B + A*7] -> [B+A*8].
3485 TestAddrMode.Scale += Scale;
3486 TestAddrMode.ScaledReg = ScaleReg;
3488 // If the new address isn't legal, bail out.
3489 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))