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;
157 // XXX-comment:We need DominatorTree to figure out which instruction to
162 static char ID; // Pass identification, replacement for typeid
163 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
164 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr),
166 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
168 bool runOnFunction(Function &F) override;
170 const char *getPassName() const override { return "CodeGen Prepare"; }
172 void getAnalysisUsage(AnalysisUsage &AU) const override {
173 AU.addPreserved<DominatorTreeWrapperPass>();
174 AU.addRequired<TargetLibraryInfoWrapperPass>();
175 AU.addRequired<TargetTransformInfoWrapperPass>();
176 AU.addRequired<DominatorTreeWrapperPass>();
180 bool eliminateFallThrough(Function &F);
181 bool eliminateMostlyEmptyBlocks(Function &F);
182 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
183 void eliminateMostlyEmptyBlock(BasicBlock *BB);
184 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
185 bool optimizeInst(Instruction *I, bool& ModifiedDT);
186 bool optimizeMemoryInst(Instruction *I, Value *Addr,
187 Type *AccessTy, unsigned AS);
188 bool optimizeInlineAsmInst(CallInst *CS);
189 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
190 bool moveExtToFormExtLoad(Instruction *&I);
191 bool optimizeExtUses(Instruction *I);
192 bool optimizeLoadExt(LoadInst *I);
193 bool optimizeSelectInst(SelectInst *SI);
194 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
195 bool optimizeSwitchInst(SwitchInst *CI);
196 bool optimizeExtractElementInst(Instruction *Inst);
197 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
198 bool placeDbgValues(Function &F);
199 bool sinkAndCmp(Function &F);
200 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
202 const SmallVectorImpl<Instruction *> &Exts,
203 unsigned CreatedInstCost);
204 bool splitBranchCondition(Function &F);
205 bool simplifyOffsetableRelocate(Instruction &I);
206 void stripInvariantGroupMetadata(Instruction &I);
210 char CodeGenPrepare::ID = 0;
211 INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
212 "Optimize for code generation", false, false)
213 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
214 INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
215 "Optimize for code generation", false, false)
217 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
218 return new CodeGenPrepare(TM);
223 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal);
224 Value* GetUntaintedAddress(Value* CurrentAddress);
226 // The depth we trace down a variable to look for its dependence set.
227 const unsigned kDependenceDepth = 4;
229 // Recursively looks for variables that 'Val' depends on at the given depth
230 // 'Depth', and adds them in 'DepSet'. If 'InsertOnlyLeafNodes' is true, only
231 // inserts the leaf node values; otherwise, all visited nodes are included in
232 // 'DepSet'. Note that constants will be ignored.
233 template <typename SetType>
234 void recursivelyFindDependence(SetType* DepSet, Value* Val,
235 bool InsertOnlyLeafNodes = false,
236 unsigned Depth = kDependenceDepth) {
237 if (Val == nullptr) {
240 if (!InsertOnlyLeafNodes && !isa<Constant>(Val)) {
244 // Cannot go deeper. Insert the leaf nodes.
245 if (InsertOnlyLeafNodes && !isa<Constant>(Val)) {
251 // Go one step further to explore the dependence of the operands.
252 Instruction* I = nullptr;
253 if ((I = dyn_cast<Instruction>(Val))) {
254 if (isa<LoadInst>(I)) {
255 // A load is considerd the leaf load of the dependence tree. Done.
258 } else if (I->isBinaryOp()) {
259 BinaryOperator* I = dyn_cast<BinaryOperator>(Val);
260 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
261 recursivelyFindDependence(DepSet, Op0, InsertOnlyLeafNodes, Depth - 1);
262 recursivelyFindDependence(DepSet, Op1, InsertOnlyLeafNodes, Depth - 1);
263 } else if (I->isCast()) {
264 Value* Op0 = I->getOperand(0);
265 recursivelyFindDependence(DepSet, Op0, InsertOnlyLeafNodes, Depth - 1);
266 } else if (I->getOpcode() == Instruction::Select) {
267 Value* Op0 = I->getOperand(0);
268 Value* Op1 = I->getOperand(1);
269 Value* Op2 = I->getOperand(2);
270 recursivelyFindDependence(DepSet, Op0, InsertOnlyLeafNodes, Depth - 1);
271 recursivelyFindDependence(DepSet, Op1, InsertOnlyLeafNodes, Depth - 1);
272 recursivelyFindDependence(DepSet, Op2, InsertOnlyLeafNodes, Depth - 1);
273 } else if (I->getOpcode() == Instruction::GetElementPtr) {
274 for (unsigned i = 0; i < I->getNumOperands(); i++) {
275 recursivelyFindDependence(DepSet, I->getOperand(i), InsertOnlyLeafNodes,
278 } else if (I->getOpcode() == Instruction::Store) {
279 auto* SI = dyn_cast<StoreInst>(Val);
280 recursivelyFindDependence(DepSet, SI->getPointerOperand(),
281 InsertOnlyLeafNodes, Depth - 1);
282 recursivelyFindDependence(DepSet, SI->getValueOperand(),
283 InsertOnlyLeafNodes, Depth - 1);
285 Value* Op0 = nullptr;
286 Value* Op1 = nullptr;
287 switch (I->getOpcode()) {
288 case Instruction::ICmp:
289 case Instruction::FCmp: {
290 Op0 = I->getOperand(0);
291 Op1 = I->getOperand(1);
292 recursivelyFindDependence(DepSet, Op0, InsertOnlyLeafNodes,
294 recursivelyFindDependence(DepSet, Op1, InsertOnlyLeafNodes,
298 case Instruction::PHI: {
299 for (int i = 0; i < I->getNumOperands(); i++) {
300 auto* op = I->getOperand(i);
301 if (DepSet->count(op) == 0) {
302 recursivelyFindDependence(DepSet, I->getOperand(i),
303 InsertOnlyLeafNodes, Depth - 1);
309 // Be conservative. Add it and be done with it.
315 } else if (isa<Constant>(Val)) {
316 // Not interested in constant values. Done.
319 // Be conservative. Add it and be done with it.
325 // Helper function to create a Cast instruction.
326 Value* createCast(IRBuilder<true, NoFolder>& Builder, Value* DepVal,
327 Type* TargetIntegerType) {
328 Instruction::CastOps CastOp = Instruction::BitCast;
329 switch (DepVal->getType()->getTypeID()) {
330 case Type::IntegerTyID: {
331 assert(TargetIntegerType->getTypeID() == Type::IntegerTyID);
332 auto* FromType = dyn_cast<IntegerType>(DepVal->getType());
333 auto* ToType = dyn_cast<IntegerType>(TargetIntegerType);
334 assert(FromType && ToType);
335 if (FromType->getBitWidth() <= ToType->getBitWidth()) {
336 CastOp = Instruction::ZExt;
338 CastOp = Instruction::Trunc;
342 case Type::FloatTyID:
343 case Type::DoubleTyID: {
344 CastOp = Instruction::FPToSI;
347 case Type::PointerTyID: {
348 CastOp = Instruction::PtrToInt;
354 return Builder.CreateCast(CastOp, DepVal, TargetIntegerType);
357 // Given a value, if it's a tainted address, this function returns the
358 // instruction that ORs the "dependence value" with the "original address".
359 // Otherwise, returns nullptr. This instruction is the first OR instruction
360 // where one of its operand is an AND instruction with an operand being 0.
362 // E.g., it returns '%4 = or i32 %3, %2' given 'CurrentAddress' is '%5'.
363 // %0 = load i32, i32* @y, align 4, !tbaa !1
364 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
365 // %1 = sext i1 %cmp to i32
366 // %2 = ptrtoint i32* @x to i32
367 // %3 = and i32 %1, 0
368 // %4 = or i32 %3, %2
369 // %5 = inttoptr i32 %4 to i32*
370 // store i32 1, i32* %5, align 4
371 Instruction* getOrAddress(Value* CurrentAddress) {
372 // Is it a cast from integer to pointer type.
373 Instruction* OrAddress = nullptr;
374 Instruction* AndDep = nullptr;
375 Instruction* CastToInt = nullptr;
376 Value* ActualAddress = nullptr;
377 Constant* ZeroConst = nullptr;
379 const Instruction* CastToPtr = dyn_cast<Instruction>(CurrentAddress);
380 if (CastToPtr && CastToPtr->getOpcode() == Instruction::IntToPtr) {
381 // Is it an OR instruction: %1 = or %and, %actualAddress.
382 if ((OrAddress = dyn_cast<Instruction>(CastToPtr->getOperand(0))) &&
383 OrAddress->getOpcode() == Instruction::Or) {
384 // The first operand should be and AND instruction.
385 AndDep = dyn_cast<Instruction>(OrAddress->getOperand(0));
386 if (AndDep && AndDep->getOpcode() == Instruction::And) {
387 // Also make sure its first operand of the "AND" is 0, or the "AND" is
388 // marked explicitly by "NoInstCombine".
389 if ((ZeroConst = dyn_cast<Constant>(AndDep->getOperand(1))) &&
390 ZeroConst->isNullValue()) {
396 // Looks like it's not been tainted.
400 // Given a value, if it's a tainted address, this function returns the
401 // instruction that taints the "dependence value". Otherwise, returns nullptr.
402 // This instruction is the last AND instruction where one of its operand is 0.
403 // E.g., it returns '%3' given 'CurrentAddress' is '%5'.
404 // %0 = load i32, i32* @y, align 4, !tbaa !1
405 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
406 // %1 = sext i1 %cmp to i32
407 // %2 = ptrtoint i32* @x to i32
408 // %3 = and i32 %1, 0
409 // %4 = or i32 %3, %2
410 // %5 = inttoptr i32 %4 to i32*
411 // store i32 1, i32* %5, align 4
412 Instruction* getAndDependence(Value* CurrentAddress) {
413 // If 'CurrentAddress' is tainted, get the OR instruction.
414 auto* OrAddress = getOrAddress(CurrentAddress);
415 if (OrAddress == nullptr) {
419 // No need to check the operands.
420 auto* AndDepInst = dyn_cast<Instruction>(OrAddress->getOperand(0));
425 // Given a value, if it's a tainted address, this function returns
426 // the "dependence value", which is the first operand in the AND instruction.
427 // E.g., it returns '%1' given 'CurrentAddress' is '%5'.
428 // %0 = load i32, i32* @y, align 4, !tbaa !1
429 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
430 // %1 = sext i1 %cmp to i32
431 // %2 = ptrtoint i32* @x to i32
432 // %3 = and i32 %1, 0
433 // %4 = or i32 %3, %2
434 // %5 = inttoptr i32 %4 to i32*
435 // store i32 1, i32* %5, align 4
436 Value* getDependence(Value* CurrentAddress) {
437 auto* AndInst = getAndDependence(CurrentAddress);
438 if (AndInst == nullptr) {
441 return AndInst->getOperand(0);
444 // Given an address that has been tainted, returns the only condition it depends
445 // on, if any; otherwise, returns nullptr.
446 Value* getConditionDependence(Value* Address) {
447 auto* Dep = getDependence(Address);
448 if (Dep == nullptr) {
449 // 'Address' has not been dependence-tainted.
453 Value* Operand = Dep;
455 auto* Inst = dyn_cast<Instruction>(Operand);
456 if (Inst == nullptr) {
457 // Non-instruction type does not have condition dependence.
460 if (Inst->getOpcode() == Instruction::ICmp) {
463 if (Inst->getNumOperands() != 1) {
466 Operand = Inst->getOperand(0);
472 // Conservatively decides whether the dependence set of 'Val1' includes the
473 // dependence set of 'Val2'. If 'ExpandSecondValue' is false, we do not expand
474 // 'Val2' and use that single value as its dependence set.
475 // If it returns true, it means the dependence set of 'Val1' includes that of
476 // 'Val2'; otherwise, it only means we cannot conclusively decide it.
477 bool dependenceSetInclusion(Value* Val1, Value* Val2,
478 int Val1ExpandLevel = 2 * kDependenceDepth,
479 int Val2ExpandLevel = kDependenceDepth) {
480 typedef SmallSet<Value*, 8> IncludingSet;
481 typedef SmallSet<Value*, 4> IncludedSet;
483 IncludingSet DepSet1;
485 // Look for more depths for the including set.
486 recursivelyFindDependence(&DepSet1, Val1, false /*Insert all visited nodes*/,
488 recursivelyFindDependence(&DepSet2, Val2, true /*Only insert leaf nodes*/,
491 auto set_inclusion = [](IncludingSet FullSet, IncludedSet Subset) {
492 for (auto* Dep : Subset) {
493 if (0 == FullSet.count(Dep)) {
499 bool inclusion = set_inclusion(DepSet1, DepSet2);
500 DEBUG(dbgs() << "[dependenceSetInclusion]: " << inclusion << "\n");
501 DEBUG(dbgs() << "Including set for: " << *Val1 << "\n");
502 DEBUG(for (const auto* Dep : DepSet1) { dbgs() << "\t\t" << *Dep << "\n"; });
503 DEBUG(dbgs() << "Included set for: " << *Val2 << "\n");
504 DEBUG(for (const auto* Dep : DepSet2) { dbgs() << "\t\t" << *Dep << "\n"; });
509 // Recursively iterates through the operands spawned from 'DepVal'. If there
510 // exists a single value that 'DepVal' only depends on, we call that value the
511 // root dependence of 'DepVal' and return it. Otherwise, return 'DepVal'.
512 Value* getRootDependence(Value* DepVal) {
513 SmallSet<Value*, 8> DepSet;
514 for (unsigned depth = kDependenceDepth; depth > 0; --depth) {
515 recursivelyFindDependence(&DepSet, DepVal, true /*Only insert leaf nodes*/,
517 if (DepSet.size() == 1) {
518 return *DepSet.begin();
525 // This function actually taints 'DepVal' to the address to 'SI'. If the
527 // of 'SI' already depends on whatever 'DepVal' depends on, this function
528 // doesn't do anything and returns false. Otherwise, returns true.
530 // This effect forces the store and any stores that comes later to depend on
531 // 'DepVal'. For example, we have a condition "cond", and a store instruction
532 // "s: STORE addr, val". If we want "s" (and any later store) to depend on
533 // "cond", we do the following:
534 // %conv = sext i1 %cond to i32
535 // %addrVal = ptrtoint i32* %addr to i32
536 // %andCond = and i32 conv, 0;
537 // %orAddr = or i32 %andCond, %addrVal;
538 // %NewAddr = inttoptr i32 %orAddr to i32*;
540 // This is a more concrete example:
542 // %0 = load i32, i32* @y, align 4, !tbaa !1
543 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
544 // %1 = sext i1 %cmp to i32
545 // %2 = ptrtoint i32* @x to i32
546 // %3 = and i32 %1, 0
547 // %4 = or i32 %3, %2
548 // %5 = inttoptr i32 %4 to i32*
549 // store i32 1, i32* %5, align 4
550 bool taintStoreAddress(StoreInst* SI, Value* DepVal) {
551 // Set the insertion point right after the 'DepVal'.
552 Instruction* Inst = nullptr;
553 IRBuilder<true, NoFolder> Builder(SI);
554 BasicBlock* BB = SI->getParent();
555 Value* Address = SI->getPointerOperand();
556 Type* TargetIntegerType =
557 IntegerType::get(Address->getContext(),
558 BB->getModule()->getDataLayout().getPointerSizeInBits());
560 // Does SI's address already depends on whatever 'DepVal' depends on?
561 if (StoreAddressDependOnValue(SI, DepVal)) {
565 // Figure out if there's a root variable 'DepVal' depends on. For example, we
566 // can extract "getelementptr inbounds %struct, %struct* %0, i64 0, i32 123"
567 // to be "%struct* %0" since all other operands are constant.
568 auto* RootVal = getRootDependence(DepVal);
569 auto* RootInst = dyn_cast<Instruction>(RootVal);
570 auto* DepValInst = dyn_cast<Instruction>(DepVal);
571 if (RootInst && DepValInst &&
572 RootInst->getParent() == DepValInst->getParent()) {
576 // Is this already a dependence-tainted store?
577 Value* OldDep = getDependence(Address);
579 // The address of 'SI' has already been tainted. Just need to absorb the
580 // DepVal to the existing dependence in the address of SI.
581 Instruction* AndDep = getAndDependence(Address);
582 IRBuilder<true, NoFolder> Builder(AndDep);
583 Value* NewDep = nullptr;
584 if (DepVal->getType() == AndDep->getType()) {
585 NewDep = Builder.CreateAnd(OldDep, DepVal);
587 NewDep = Builder.CreateAnd(
588 OldDep, createCast(Builder, DepVal, TargetIntegerType));
591 auto* NewDepInst = dyn_cast<Instruction>(NewDep);
593 // Use the new AND instruction as the dependence
594 AndDep->setOperand(0, NewDep);
598 // SI's address has not been tainted. Now taint it with 'DepVal'.
599 Value* CastDepToInt = createCast(Builder, DepVal, TargetIntegerType);
600 Value* PtrToIntCast = Builder.CreatePtrToInt(Address, TargetIntegerType);
602 Builder.CreateAnd(CastDepToInt, ConstantInt::get(TargetIntegerType, 0));
603 auto AndInst = dyn_cast<Instruction>(AndDepVal);
604 // XXX-comment: The original IR InstCombiner would change our and instruction
605 // to a select and then the back end optimize the condition out. We attach a
606 // flag to instructions and set it here to inform the InstCombiner to not to
607 // touch this and instruction at all.
608 Value* OrAddr = Builder.CreateOr(AndDepVal, PtrToIntCast);
609 Value* NewAddr = Builder.CreateIntToPtr(OrAddr, Address->getType());
611 DEBUG(dbgs() << "[taintStoreAddress]\n"
612 << "Original store: " << *SI << '\n');
613 SI->setOperand(1, NewAddr);
616 DEBUG(dbgs() << "\tTargetIntegerType: " << *TargetIntegerType << '\n'
617 << "\tCast dependence value to integer: " << *CastDepToInt
619 << "\tCast address to integer: " << *PtrToIntCast << '\n'
620 << "\tAnd dependence value: " << *AndDepVal << '\n'
621 << "\tOr address: " << *OrAddr << '\n'
622 << "\tCast or instruction to address: " << *NewAddr << "\n\n");
627 // Looks for the previous store in the if block --- 'BrBB', which makes the
628 // speculative store 'StoreToHoist' safe.
629 Value* getSpeculativeStoreInPrevBB(StoreInst* StoreToHoist, BasicBlock* BrBB) {
630 assert(StoreToHoist && "StoreToHoist must be a real store");
632 Value* StorePtr = StoreToHoist->getPointerOperand();
634 // Look for a store to the same pointer in BrBB.
635 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), RE = BrBB->rend();
637 Instruction* CurI = &*RI;
639 StoreInst* SI = dyn_cast<StoreInst>(CurI);
640 // Found the previous store make sure it stores to the same location.
641 // XXX-update: If the previous store's original untainted address are the
642 // same as 'StorePtr', we are also good to hoist the store.
643 if (SI && (SI->getPointerOperand() == StorePtr ||
644 GetUntaintedAddress(SI->getPointerOperand()) == StorePtr)) {
645 // Found the previous store, return its value operand.
651 "We should not reach here since this store is safe to speculate");
654 // XXX-comment: Returns true if it changes the code, false otherwise (the branch
655 // condition already depends on 'DepVal'.
656 bool taintConditionalBranch(BranchInst* BI, Value* DepVal) {
657 assert(BI->isConditional());
658 auto* Cond = BI->getOperand(0);
659 if (dependenceSetInclusion(Cond, DepVal)) {
660 // The dependence/ordering is self-evident.
664 IRBuilder<true, NoFolder> Builder(BI);
666 Builder.CreateAnd(DepVal, ConstantInt::get(DepVal->getType(), 0));
668 Builder.CreateTrunc(AndDep, IntegerType::get(DepVal->getContext(), 1));
669 auto* OrCond = Builder.CreateOr(TruncAndDep, Cond);
670 BI->setOperand(0, OrCond);
673 DEBUG(dbgs() << "\tTainted branch condition:\n" << *BI->getParent());
678 bool ConditionalBranchDependsOnValue(BranchInst* BI, Value* DepVal) {
679 assert(BI->isConditional());
680 auto* Cond = BI->getOperand(0);
681 return dependenceSetInclusion(Cond, DepVal);
684 // XXX-update: For a relaxed load 'LI', find the first immediate atomic store or
685 // the first conditional branch. Returns nullptr if there's no such immediately
686 // following store/branch instructions, which we can only enforce the load with
687 // 'acquire'. 'ChainedBB' contains all the blocks chained together with
688 // unconditional branches from 'BB' to the block with the first store/cond
690 template <typename Vector>
691 Instruction* findFirstStoreCondBranchInst(LoadInst* LI, Vector* ChainedBB) {
692 // In some situations, relaxed loads can be left as is:
693 // 1. The relaxed load is used to calculate the address of the immediate
695 // 2. The relaxed load is used as a condition in the immediate following
696 // condition, and there are no stores in between. This is actually quite
698 // int r1 = x.load(relaxed);
700 // y.store(1, relaxed);
702 // However, in this function, we don't deal with them directly. Instead, we
703 // just find the immediate following store/condition branch and return it.
705 assert(ChainedBB != nullptr && "Chained BB should not be nullptr");
706 auto* BB = LI->getParent();
707 ChainedBB->push_back(BB);
709 auto BBI = BasicBlock::iterator(LI);
712 for (; BBI != BE; BBI++) {
713 auto* Inst = dyn_cast<Instruction>(&*BBI);
714 if (Inst == nullptr) {
717 if (Inst->getOpcode() == Instruction::Store) {
719 } else if (Inst->getOpcode() == Instruction::Br) {
720 auto* BrInst = dyn_cast<BranchInst>(Inst);
721 if (BrInst->isConditional()) {
724 // Reinitialize iterators with the destination of the unconditional
726 BB = BrInst->getSuccessor(0);
727 ChainedBB->push_back(BB);
740 // XXX-update: Find the next node of the last relaxed load from 'FromInst' to
741 // 'ToInst'. If none, return 'ToInst'.
742 Instruction* findLastLoadNext(Instruction* FromInst, Instruction* ToInst) {
743 if (FromInst == ToInst) {
746 Instruction* LastLoad = ToInst;
747 auto* BB = FromInst->getParent();
749 auto BBI = BasicBlock::iterator(FromInst);
751 for (; BBI != BE && &*BBI != ToInst; BBI++) {
752 auto* LI = dyn_cast<LoadInst>(&*BBI);
753 if (LI == nullptr || !LI->isAtomic() || LI->getOrdering() != Monotonic) {
757 LastLoad = LastLoad->getNextNode();
762 // XXX-comment: Returns whether the code has been changed.
763 bool taintMonotonicLoads(const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
764 bool Changed = false;
765 for (auto* LI : MonotonicLoadInsts) {
766 SmallVector<BasicBlock*, 2> ChainedBB;
767 auto* FirstInst = findFirstStoreCondBranchInst(LI, &ChainedBB);
768 if (FirstInst == nullptr) {
769 // We don't seem to be able to taint a following store/conditional branch
770 // instruction. Simply make it acquire.
771 DEBUG(dbgs() << "[RelaxedLoad]: Transformed to acquire load\n"
773 LI->setOrdering(Acquire);
777 // Taint 'FirstInst', which could be a store or a condition branch
779 if (FirstInst->getOpcode() == Instruction::Store) {
780 Changed |= taintStoreAddress(dyn_cast<StoreInst>(FirstInst), LI);
781 } else if (FirstInst->getOpcode() == Instruction::Br) {
782 Changed |= taintConditionalBranch(dyn_cast<BranchInst>(FirstInst), LI);
784 assert(false && "findFirstStoreCondBranchInst() should return a "
785 "store/condition branch instruction");
791 // Inserts a fake conditional branch right after the instruction 'SplitInst',
792 // and the branch condition is 'Condition'. 'SplitInst' will be placed in the
793 // newly created block.
794 void AddFakeConditionalBranch(Instruction* SplitInst, Value* Condition) {
795 auto* BB = SplitInst->getParent();
796 TerminatorInst* ThenTerm = nullptr;
797 TerminatorInst* ElseTerm = nullptr;
798 SplitBlockAndInsertIfThenElse(Condition, SplitInst, &ThenTerm, &ElseTerm);
799 assert(ThenTerm && ElseTerm &&
800 "Then/Else terminators cannot be empty after basic block spliting");
801 auto* ThenBB = ThenTerm->getParent();
802 auto* ElseBB = ElseTerm->getParent();
803 auto* TailBB = ThenBB->getSingleSuccessor();
804 assert(TailBB && "Tail block cannot be empty after basic block spliting");
806 ThenBB->disableCanEliminateBlock();
807 ThenBB->disableCanEliminateBlock();
808 TailBB->disableCanEliminateBlock();
809 ThenBB->setName(BB->getName() + "Then.Fake");
810 ElseBB->setName(BB->getName() + "Else.Fake");
811 DEBUG(dbgs() << "Add fake conditional branch:\n"
813 << *ThenBB << "Else Block:\n"
817 // Returns true if the code is changed, and false otherwise.
818 void TaintRelaxedLoads(Instruction* UsageInst, Instruction* InsertPoint) {
819 // For better performance, we can add a "AND X 0" instruction before the
821 auto* BB = UsageInst->getParent();
822 if (InsertPoint == nullptr) {
823 InsertPoint = UsageInst->getNextNode();
825 // Insert instructions after PHI nodes.
826 while (dyn_cast<PHINode>(InsertPoint)) {
827 InsertPoint = InsertPoint->getNextNode();
829 // First thing is to cast 'UsageInst' to an integer type if necessary.
830 Value* AndTarget = nullptr;
831 Type* TargetIntegerType =
832 IntegerType::get(UsageInst->getContext(),
833 BB->getModule()->getDataLayout().getPointerSizeInBits());
835 // Check whether InsertPoint is a added fake conditional branch.
836 BranchInst* BI = nullptr;
837 if ((BI = dyn_cast<BranchInst>(InsertPoint)) && BI->isConditional()) {
838 auto* Cond = dyn_cast<Instruction>(BI->getOperand(0));
839 if (Cond && Cond->getOpcode() == Instruction::ICmp) {
840 auto* CmpInst = dyn_cast<ICmpInst>(Cond);
841 auto* Op0 = dyn_cast<Instruction>(Cond->getOperand(0));
842 auto* Op1 = dyn_cast<ConstantInt>(Cond->getOperand(1));
844 // %cmp = ICMP_NE %tmp, 0
847 // %tmp1 = And X, NewTaintedVal
848 // %tmp2 = And %tmp1, 0
849 // %cmp = ICMP_NE %tmp2, 0
851 if (CmpInst && CmpInst->getPredicate() == CmpInst::ICMP_NE && Op0 &&
852 Op0->getOpcode() == Instruction::And && Op1 && Op1->isZero()) {
853 auto* Op01 = dyn_cast<ConstantInt>(Op0->getOperand(1));
854 if (Op01 && Op01->isZero()) {
855 // Now we have a previously added fake cond branch.
856 auto* Op00 = Op0->getOperand(0);
857 IRBuilder<true, NoFolder> Builder(CmpInst);
858 if (Op00->getType() == UsageInst->getType()) {
859 AndTarget = UsageInst;
861 AndTarget = createCast(Builder, UsageInst, Op00->getType());
863 AndTarget = Builder.CreateAnd(Op00, AndTarget);
864 auto* AndZero = dyn_cast<Instruction>(Builder.CreateAnd(
865 AndTarget, Constant::getNullValue(AndTarget->getType())));
866 CmpInst->setOperand(0, AndZero);
873 IRBuilder<true, NoFolder> Builder(InsertPoint);
874 if (IntegerType::classof(UsageInst->getType())) {
875 AndTarget = UsageInst;
877 AndTarget = createCast(Builder, UsageInst, TargetIntegerType);
879 auto* AndZero = dyn_cast<Instruction>(
880 Builder.CreateAnd(AndTarget, Constant::getNullValue(AndTarget->getType())));
881 auto* FakeCondition = dyn_cast<Instruction>(Builder.CreateICmp(
882 CmpInst::ICMP_NE, AndZero, Constant::getNullValue(AndTarget->getType())));
883 AddFakeConditionalBranch(FakeCondition->getNextNode(), FakeCondition);
886 // XXX-comment: Finds the appropriate Value derived from an atomic load.
887 // 'ChainedBB' contains all the blocks chained together with unconditional
888 // branches from LI's parent BB to the block with the first store/cond branch.
889 // If we don't find any, it means 'LI' is not used at all (which should not
890 // happen in practice). We can simply set 'LI' to be acquire just to be safe.
891 template <typename Vector>
892 Instruction* findMostRecentDependenceUsage(LoadInst* LI, Instruction* LaterInst,
895 typedef SmallSet<Instruction*, 8> UsageSet;
896 typedef DenseMap<BasicBlock*, std::unique_ptr<UsageSet>> UsageMap;
897 assert(ChainedBB->size() >= 1 && "ChainedBB must have >=1 size");
898 // Mapping from basic block in 'ChainedBB' to the set of dependence usage of
899 // 'LI' in each block.
901 auto* LoadBB = LI->getParent();
902 usage_map[LoadBB] = make_unique<UsageSet>();
903 usage_map[LoadBB]->insert(LI);
905 for (auto* BB : *ChainedBB) {
906 if (usage_map[BB] == nullptr) {
907 usage_map[BB] = make_unique<UsageSet>();
909 auto& usage_set = usage_map[BB];
910 if (usage_set->size() == 0) {
911 // The value has not been used.
914 // Calculate the usage in the current BB first.
915 std::list<Value*> bb_usage_list;
916 std::copy(usage_set->begin(), usage_set->end(),
917 std::back_inserter(bb_usage_list));
918 for (auto list_iter = bb_usage_list.begin();
919 list_iter != bb_usage_list.end(); list_iter++) {
920 auto* val = *list_iter;
921 for (auto* U : val->users()) {
922 Instruction* Inst = nullptr;
923 if (!(Inst = dyn_cast<Instruction>(U))) {
926 assert(Inst && "Usage value must be an instruction");
928 std::find(ChainedBB->begin(), ChainedBB->end(), Inst->getParent());
929 if (iter == ChainedBB->end()) {
930 // Only care about usage within ChainedBB.
933 auto* UsageBB = *iter;
936 if (!usage_set->count(Inst)) {
937 bb_usage_list.push_back(Inst);
938 usage_set->insert(Inst);
942 if (usage_map[UsageBB] == nullptr) {
943 usage_map[UsageBB] = make_unique<UsageSet>();
945 usage_map[UsageBB]->insert(Inst);
951 // Pick one usage that is in LaterInst's block and that dominates 'LaterInst'.
952 auto* LaterBB = LaterInst->getParent();
953 auto& usage_set = usage_map[LaterBB];
954 Instruction* usage_inst = nullptr;
955 for (auto* inst : *usage_set) {
956 if (DT->dominates(inst, LaterInst)) {
962 assert(usage_inst && "The usage instruction in the same block but after the "
963 "later instruction");
967 // XXX-comment: Returns whether the code has been changed.
968 bool AddFakeConditionalBranchAfterMonotonicLoads(
969 SmallSet<LoadInst*, 1>& MonotonicLoadInsts, DominatorTree* DT) {
970 bool Changed = false;
971 while (!MonotonicLoadInsts.empty()) {
972 auto* LI = *MonotonicLoadInsts.begin();
973 MonotonicLoadInsts.erase(LI);
974 SmallVector<BasicBlock*, 2> ChainedBB;
975 auto* FirstInst = findFirstStoreCondBranchInst(LI, &ChainedBB);
976 if (FirstInst != nullptr) {
977 if (FirstInst->getOpcode() == Instruction::Store) {
978 if (StoreAddressDependOnValue(dyn_cast<StoreInst>(FirstInst), LI)) {
981 } else if (FirstInst->getOpcode() == Instruction::Br) {
982 if (ConditionalBranchDependsOnValue(dyn_cast<BranchInst>(FirstInst),
987 dbgs() << "FirstInst=" << *FirstInst << "\n";
988 assert(false && "findFirstStoreCondBranchInst() should return a "
989 "store/condition branch instruction");
993 // We really need to process the relaxed load now.
994 StoreInst* SI = nullptr;;
995 if (FirstInst && (SI = dyn_cast<StoreInst>(FirstInst))) {
996 // For immediately coming stores, taint the address of the store.
997 if (SI->getParent() == LI->getParent() || DT->dominates(LI, SI)) {
998 TaintRelaxedLoads(LI, SI);
1002 findMostRecentDependenceUsage(LI, FirstInst, &ChainedBB, DT);
1004 LI->setOrdering(Acquire);
1007 TaintRelaxedLoads(Inst, SI);
1012 // No upcoming branch
1014 TaintRelaxedLoads(LI, nullptr);
1017 // For immediately coming branch, directly add a fake branch.
1018 if (FirstInst->getParent() == LI->getParent() ||
1019 DT->dominates(LI, FirstInst)) {
1020 TaintRelaxedLoads(LI, FirstInst);
1024 findMostRecentDependenceUsage(LI, FirstInst, &ChainedBB, DT);
1026 TaintRelaxedLoads(Inst, FirstInst);
1028 LI->setOrdering(Acquire);
1038 /**** Implementations of public methods for dependence tainting ****/
1039 Value* GetUntaintedAddress(Value* CurrentAddress) {
1040 auto* OrAddress = getOrAddress(CurrentAddress);
1041 if (OrAddress == nullptr) {
1042 // Is it tainted by a select instruction?
1043 auto* Inst = dyn_cast<Instruction>(CurrentAddress);
1044 if (nullptr != Inst && Inst->getOpcode() == Instruction::Select) {
1045 // A selection instruction.
1046 if (Inst->getOperand(1) == Inst->getOperand(2)) {
1047 return Inst->getOperand(1);
1051 return CurrentAddress;
1053 Value* ActualAddress = nullptr;
1055 auto* CastToInt = dyn_cast<Instruction>(OrAddress->getOperand(1));
1056 if (CastToInt && CastToInt->getOpcode() == Instruction::PtrToInt) {
1057 return CastToInt->getOperand(0);
1059 // This should be a IntToPtr constant expression.
1060 ConstantExpr* PtrToIntExpr =
1061 dyn_cast<ConstantExpr>(OrAddress->getOperand(1));
1062 if (PtrToIntExpr && PtrToIntExpr->getOpcode() == Instruction::PtrToInt) {
1063 return PtrToIntExpr->getOperand(0);
1067 // Looks like it's not been dependence-tainted. Returns itself.
1068 return CurrentAddress;
1071 MemoryLocation GetUntaintedMemoryLocation(StoreInst* SI) {
1073 SI->getAAMetadata(AATags);
1074 const auto& DL = SI->getModule()->getDataLayout();
1075 const auto* OriginalAddr = GetUntaintedAddress(SI->getPointerOperand());
1076 DEBUG(if (OriginalAddr != SI->getPointerOperand()) {
1077 dbgs() << "[GetUntaintedMemoryLocation]\n"
1078 << "Storing address: " << *SI->getPointerOperand()
1079 << "\nUntainted address: " << *OriginalAddr << "\n";
1081 return MemoryLocation(OriginalAddr,
1082 DL.getTypeStoreSize(SI->getValueOperand()->getType()),
1086 bool TaintDependenceToStore(StoreInst* SI, Value* DepVal) {
1087 if (dependenceSetInclusion(SI, DepVal)) {
1091 bool tainted = taintStoreAddress(SI, DepVal);
1096 bool TaintDependenceToStoreAddress(StoreInst* SI, Value* DepVal) {
1097 if (dependenceSetInclusion(SI->getPointerOperand(), DepVal)) {
1101 bool tainted = taintStoreAddress(SI, DepVal);
1106 bool CompressTaintedStore(BasicBlock* BB) {
1107 // This function looks for windows of adajcent stores in 'BB' that satisfy the
1108 // following condition (and then do optimization):
1109 // *Addr(d1) = v1, d1 is a condition and is the only dependence the store's
1110 // address depends on && Dep(v1) includes Dep(d1);
1111 // *Addr(d2) = v2, d2 is a condition and is the only dependnece the store's
1112 // address depends on && Dep(v2) includes Dep(d2) &&
1113 // Dep(d2) includes Dep(d1);
1115 // *Addr(dN) = vN, dN is a condition and is the only dependence the store's
1116 // address depends on && Dep(dN) includes Dep(d"N-1").
1118 // As a result, Dep(dN) includes [Dep(d1) V ... V Dep(d"N-1")], so we can
1119 // safely transform the above to the following. In between these stores, we
1120 // can omit untainted stores to the same address 'Addr' since they internally
1121 // have dependence on the previous stores on the same address.
1126 for (auto BI = BB->begin(), BE = BB->end(); BI != BE; BI++) {
1127 // Look for the first store in such a window of adajacent stores.
1128 auto* FirstSI = dyn_cast<StoreInst>(&*BI);
1133 // The first store in the window must be tainted.
1134 auto* UntaintedAddress = GetUntaintedAddress(FirstSI->getPointerOperand());
1135 if (UntaintedAddress == FirstSI->getPointerOperand()) {
1139 // The first store's address must directly depend on and only depend on a
1141 auto* FirstSIDepCond = getConditionDependence(FirstSI->getPointerOperand());
1142 if (nullptr == FirstSIDepCond) {
1146 // Dep(first store's storing value) includes Dep(tainted dependence).
1147 if (!dependenceSetInclusion(FirstSI->getValueOperand(), FirstSIDepCond)) {
1151 // Look for subsequent stores to the same address that satisfy the condition
1152 // of "compressing the dependence".
1153 SmallVector<StoreInst*, 8> AdajacentStores;
1154 AdajacentStores.push_back(FirstSI);
1155 auto BII = BasicBlock::iterator(FirstSI);
1156 for (BII++; BII != BE; BII++) {
1157 auto* CurrSI = dyn_cast<StoreInst>(&*BII);
1159 if (BII->mayHaveSideEffects()) {
1160 // Be conservative. Instructions with side effects are similar to
1167 auto* OrigAddress = GetUntaintedAddress(CurrSI->getPointerOperand());
1168 auto* CurrSIDepCond = getConditionDependence(CurrSI->getPointerOperand());
1169 // All other stores must satisfy either:
1170 // A. 'CurrSI' is an untainted store to the same address, or
1171 // B. the combination of the following 5 subconditions:
1173 // 2. Untainted address is the same as the group's address;
1174 // 3. The address is tainted with a sole value which is a condition;
1175 // 4. The storing value depends on the condition in 3.
1176 // 5. The condition in 3 depends on the previous stores dependence
1179 // Condition A. Should ignore this store directly.
1180 if (OrigAddress == CurrSI->getPointerOperand() &&
1181 OrigAddress == UntaintedAddress) {
1184 // Check condition B.
1185 Value* Cond = nullptr;
1186 if (OrigAddress == CurrSI->getPointerOperand() ||
1187 OrigAddress != UntaintedAddress || CurrSIDepCond == nullptr ||
1188 !dependenceSetInclusion(CurrSI->getValueOperand(), CurrSIDepCond)) {
1189 // Check condition 1, 2, 3 & 4.
1193 // Check condition 5.
1194 StoreInst* PrevSI = AdajacentStores[AdajacentStores.size() - 1];
1195 auto* PrevSIDepCond = getConditionDependence(PrevSI->getPointerOperand());
1196 assert(PrevSIDepCond &&
1197 "Store in the group must already depend on a condtion");
1198 if (!dependenceSetInclusion(CurrSIDepCond, PrevSIDepCond)) {
1202 AdajacentStores.push_back(CurrSI);
1205 if (AdajacentStores.size() == 1) {
1206 // The outer loop should keep looking from the next store.
1210 // Now we have such a group of tainted stores to the same address.
1211 DEBUG(dbgs() << "[CompressTaintedStore]\n");
1212 DEBUG(dbgs() << "Original BB\n");
1213 DEBUG(dbgs() << *BB << '\n');
1214 auto* LastSI = AdajacentStores[AdajacentStores.size() - 1];
1215 for (unsigned i = 0; i < AdajacentStores.size() - 1; ++i) {
1216 auto* SI = AdajacentStores[i];
1218 // Use the original address for stores before the last one.
1219 SI->setOperand(1, UntaintedAddress);
1221 DEBUG(dbgs() << "Store address has been reversed: " << *SI << '\n';);
1223 // XXX-comment: Try to make the last store use fewer registers.
1224 // If LastSI's storing value is a select based on the condition with which
1225 // its address is tainted, transform the tainted address to a select
1226 // instruction, as follows:
1227 // r1 = Select Cond ? A : B
1232 // r1 = Select Cond ? A : B
1233 // r2 = Select Cond ? Addr : Addr
1235 // The idea is that both Select instructions depend on the same condition,
1236 // so hopefully the backend can generate two cmov instructions for them (and
1237 // this saves the number of registers needed).
1238 auto* LastSIDep = getConditionDependence(LastSI->getPointerOperand());
1239 auto* LastSIValue = dyn_cast<Instruction>(LastSI->getValueOperand());
1240 if (LastSIValue && LastSIValue->getOpcode() == Instruction::Select &&
1241 LastSIValue->getOperand(0) == LastSIDep) {
1242 // XXX-comment: Maybe it's better for us to just leave it as an and/or
1243 // dependence pattern.
1245 IRBuilder<true, NoFolder> Builder(LastSI);
1247 Builder.CreateSelect(LastSIDep, UntaintedAddress, UntaintedAddress);
1248 LastSI->setOperand(1, Address);
1249 DEBUG(dbgs() << "The last store becomes :" << *LastSI << "\n\n";);
1257 bool PassDependenceToStore(Value* OldAddress, StoreInst* NewStore) {
1258 Value* OldDep = getDependence(OldAddress);
1259 // Return false when there's no dependence to pass from the OldAddress.
1264 // No need to pass the dependence to NewStore's address if it already depends
1265 // on whatever 'OldAddress' depends on.
1266 if (StoreAddressDependOnValue(NewStore, OldDep)) {
1269 return taintStoreAddress(NewStore, OldAddress);
1272 SmallSet<Value*, 8> FindDependence(Value* Val) {
1273 SmallSet<Value*, 8> DepSet;
1274 recursivelyFindDependence(&DepSet, Val, true /*Only insert leaf nodes*/);
1278 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal) {
1279 return dependenceSetInclusion(SI->getPointerOperand(), DepVal);
1282 bool StoreDependOnValue(StoreInst* SI, Value* Dep) {
1283 return dependenceSetInclusion(SI, Dep);
1290 bool CodeGenPrepare::runOnFunction(Function &F) {
1291 bool EverMadeChange = false;
1293 if (skipOptnoneFunction(F))
1296 DL = &F.getParent()->getDataLayout();
1298 // Clear per function information.
1299 InsertedInsts.clear();
1300 PromotedInsts.clear();
1304 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
1305 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1306 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1307 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1308 OptSize = F.optForSize();
1310 /// This optimization identifies DIV instructions that can be
1311 /// profitably bypassed and carried out with a shorter, faster divide.
1312 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
1313 const DenseMap<unsigned int, unsigned int> &BypassWidths =
1314 TLI->getBypassSlowDivWidths();
1315 BasicBlock* BB = &*F.begin();
1316 while (BB != nullptr) {
1317 // bypassSlowDivision may create new BBs, but we don't want to reapply the
1318 // optimization to those blocks.
1319 BasicBlock* Next = BB->getNextNode();
1320 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
1325 // Eliminate blocks that contain only PHI nodes and an
1326 // unconditional branch.
1327 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
1329 // llvm.dbg.value is far away from the value then iSel may not be able
1330 // handle it properly. iSel will drop llvm.dbg.value if it can not
1331 // find a node corresponding to the value.
1332 EverMadeChange |= placeDbgValues(F);
1334 // If there is a mask, compare against zero, and branch that can be combined
1335 // into a single target instruction, push the mask and compare into branch
1336 // users. Do this before OptimizeBlock -> OptimizeInst ->
1337 // OptimizeCmpExpression, which perturbs the pattern being searched for.
1338 if (!DisableBranchOpts) {
1339 EverMadeChange |= sinkAndCmp(F);
1340 EverMadeChange |= splitBranchCondition(F);
1343 bool MadeChange = true;
1344 while (MadeChange) {
1346 for (Function::iterator I = F.begin(); I != F.end(); ) {
1347 BasicBlock *BB = &*I++;
1348 bool ModifiedDTOnIteration = false;
1349 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
1351 // Restart BB iteration if the dominator tree of the Function was changed
1352 if (ModifiedDTOnIteration)
1355 EverMadeChange |= MadeChange;
1360 if (!DisableBranchOpts) {
1362 SmallPtrSet<BasicBlock*, 8> WorkList;
1363 for (BasicBlock &BB : F) {
1364 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
1365 MadeChange |= ConstantFoldTerminator(&BB, true);
1366 if (!MadeChange) continue;
1368 for (SmallVectorImpl<BasicBlock*>::iterator
1369 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1370 if (pred_begin(*II) == pred_end(*II))
1371 WorkList.insert(*II);
1374 // Delete the dead blocks and any of their dead successors.
1375 MadeChange |= !WorkList.empty();
1376 while (!WorkList.empty()) {
1377 BasicBlock *BB = *WorkList.begin();
1379 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
1381 DeleteDeadBlock(BB);
1383 for (SmallVectorImpl<BasicBlock*>::iterator
1384 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1385 if (pred_begin(*II) == pred_end(*II))
1386 WorkList.insert(*II);
1389 // Merge pairs of basic blocks with unconditional branches, connected by
1391 if (EverMadeChange || MadeChange)
1392 MadeChange |= eliminateFallThrough(F);
1394 EverMadeChange |= MadeChange;
1397 if (!DisableGCOpts) {
1398 SmallVector<Instruction *, 2> Statepoints;
1399 for (BasicBlock &BB : F)
1400 for (Instruction &I : BB)
1401 if (isStatepoint(I))
1402 Statepoints.push_back(&I);
1403 for (auto &I : Statepoints)
1404 EverMadeChange |= simplifyOffsetableRelocate(*I);
1407 // XXX-comment: Delay dealing with relaxed loads in this function to avoid
1408 // further changes done by other passes (e.g., SimplifyCFG).
1409 // Collect all the relaxed loads.
1410 SmallSet<LoadInst*, 1> MonotonicLoadInsts;
1411 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
1412 if (I->isAtomic()) {
1413 switch (I->getOpcode()) {
1414 case Instruction::Load: {
1415 auto* LI = dyn_cast<LoadInst>(&*I);
1416 if (LI->getOrdering() == Monotonic &&
1417 !LI->getHasSubsequentAcqlRMW()) {
1418 MonotonicLoadInsts.insert(LI);
1429 AddFakeConditionalBranchAfterMonotonicLoads(MonotonicLoadInsts, DT);
1431 return EverMadeChange;
1434 /// Merge basic blocks which are connected by a single edge, where one of the
1435 /// basic blocks has a single successor pointing to the other basic block,
1436 /// which has a single predecessor.
1437 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
1438 bool Changed = false;
1439 // Scan all of the blocks in the function, except for the entry block.
1440 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1441 BasicBlock *BB = &*I++;
1442 // If the destination block has a single pred, then this is a trivial
1443 // edge, just collapse it.
1444 BasicBlock *SinglePred = BB->getSinglePredecessor();
1446 // Don't merge if BB's address is taken.
1447 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
1449 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
1450 if (Term && !Term->isConditional()) {
1452 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
1453 // Remember if SinglePred was the entry block of the function.
1454 // If so, we will need to move BB back to the entry position.
1455 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1456 MergeBasicBlockIntoOnlyPred(BB, nullptr);
1458 if (isEntry && BB != &BB->getParent()->getEntryBlock())
1459 BB->moveBefore(&BB->getParent()->getEntryBlock());
1461 // We have erased a block. Update the iterator.
1462 I = BB->getIterator();
1468 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
1469 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
1470 /// edges in ways that are non-optimal for isel. Start by eliminating these
1471 /// blocks so we can split them the way we want them.
1472 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
1473 bool MadeChange = false;
1474 // Note that this intentionally skips the entry block.
1475 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1476 BasicBlock *BB = &*I++;
1477 // If this block doesn't end with an uncond branch, ignore it.
1478 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
1479 if (!BI || !BI->isUnconditional())
1482 // If the instruction before the branch (skipping debug info) isn't a phi
1483 // node, then other stuff is happening here.
1484 BasicBlock::iterator BBI = BI->getIterator();
1485 if (BBI != BB->begin()) {
1487 while (isa<DbgInfoIntrinsic>(BBI)) {
1488 if (BBI == BB->begin())
1492 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
1496 // Do not break infinite loops.
1497 BasicBlock *DestBB = BI->getSuccessor(0);
1501 if (!canMergeBlocks(BB, DestBB))
1504 eliminateMostlyEmptyBlock(BB);
1510 /// Return true if we can merge BB into DestBB if there is a single
1511 /// unconditional branch between them, and BB contains no other non-phi
1513 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1514 const BasicBlock *DestBB) const {
1515 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1516 // the successor. If there are more complex condition (e.g. preheaders),
1517 // don't mess around with them.
1518 BasicBlock::const_iterator BBI = BB->begin();
1519 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1520 for (const User *U : PN->users()) {
1521 const Instruction *UI = cast<Instruction>(U);
1522 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1524 // IfUser is inside DestBB block and it is a PHINode then check
1525 // incoming value. If incoming value is not from BB then this is
1526 // a complex condition (e.g. preheaders) we want to avoid here.
1527 if (UI->getParent() == DestBB) {
1528 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1529 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1530 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1531 if (Insn && Insn->getParent() == BB &&
1532 Insn->getParent() != UPN->getIncomingBlock(I))
1539 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1540 // and DestBB may have conflicting incoming values for the block. If so, we
1541 // can't merge the block.
1542 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1543 if (!DestBBPN) return true; // no conflict.
1545 // Collect the preds of BB.
1546 SmallPtrSet<const BasicBlock*, 16> BBPreds;
1547 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1548 // It is faster to get preds from a PHI than with pred_iterator.
1549 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1550 BBPreds.insert(BBPN->getIncomingBlock(i));
1552 BBPreds.insert(pred_begin(BB), pred_end(BB));
1555 // Walk the preds of DestBB.
1556 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1557 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1558 if (BBPreds.count(Pred)) { // Common predecessor?
1559 BBI = DestBB->begin();
1560 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1561 const Value *V1 = PN->getIncomingValueForBlock(Pred);
1562 const Value *V2 = PN->getIncomingValueForBlock(BB);
1564 // If V2 is a phi node in BB, look up what the mapped value will be.
1565 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1566 if (V2PN->getParent() == BB)
1567 V2 = V2PN->getIncomingValueForBlock(Pred);
1569 // If there is a conflict, bail out.
1570 if (V1 != V2) return false;
1579 /// Eliminate a basic block that has only phi's and an unconditional branch in
1581 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1582 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1583 BasicBlock *DestBB = BI->getSuccessor(0);
1585 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
1587 // If the destination block has a single pred, then this is a trivial edge,
1588 // just collapse it.
1589 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1590 if (SinglePred != DestBB) {
1591 // Remember if SinglePred was the entry block of the function. If so, we
1592 // will need to move BB back to the entry position.
1593 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1594 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
1596 if (isEntry && BB != &BB->getParent()->getEntryBlock())
1597 BB->moveBefore(&BB->getParent()->getEntryBlock());
1599 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1604 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1605 // to handle the new incoming edges it is about to have.
1607 for (BasicBlock::iterator BBI = DestBB->begin();
1608 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1609 // Remove the incoming value for BB, and remember it.
1610 Value *InVal = PN->removeIncomingValue(BB, false);
1612 // Two options: either the InVal is a phi node defined in BB or it is some
1613 // value that dominates BB.
1614 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1615 if (InValPhi && InValPhi->getParent() == BB) {
1616 // Add all of the input values of the input PHI as inputs of this phi.
1617 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1618 PN->addIncoming(InValPhi->getIncomingValue(i),
1619 InValPhi->getIncomingBlock(i));
1621 // Otherwise, add one instance of the dominating value for each edge that
1622 // we will be adding.
1623 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1624 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1625 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
1627 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1628 PN->addIncoming(InVal, *PI);
1633 // The PHIs are now updated, change everything that refers to BB to use
1634 // DestBB and remove BB.
1635 BB->replaceAllUsesWith(DestBB);
1636 BB->eraseFromParent();
1639 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1642 // Computes a map of base pointer relocation instructions to corresponding
1643 // derived pointer relocation instructions given a vector of all relocate calls
1644 static void computeBaseDerivedRelocateMap(
1645 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1646 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1648 // Collect information in two maps: one primarily for locating the base object
1649 // while filling the second map; the second map is the final structure holding
1650 // a mapping between Base and corresponding Derived relocate calls
1651 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1652 for (auto *ThisRelocate : AllRelocateCalls) {
1653 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1654 ThisRelocate->getDerivedPtrIndex());
1655 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1657 for (auto &Item : RelocateIdxMap) {
1658 std::pair<unsigned, unsigned> Key = Item.first;
1659 if (Key.first == Key.second)
1660 // Base relocation: nothing to insert
1663 GCRelocateInst *I = Item.second;
1664 auto BaseKey = std::make_pair(Key.first, Key.first);
1666 // We're iterating over RelocateIdxMap so we cannot modify it.
1667 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1668 if (MaybeBase == RelocateIdxMap.end())
1669 // TODO: We might want to insert a new base object relocate and gep off
1670 // that, if there are enough derived object relocates.
1673 RelocateInstMap[MaybeBase->second].push_back(I);
1677 // Accepts a GEP and extracts the operands into a vector provided they're all
1678 // small integer constants
1679 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1680 SmallVectorImpl<Value *> &OffsetV) {
1681 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1682 // Only accept small constant integer operands
1683 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1684 if (!Op || Op->getZExtValue() > 20)
1688 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1689 OffsetV.push_back(GEP->getOperand(i));
1693 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1694 // replace, computes a replacement, and affects it.
1696 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1697 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1698 bool MadeChange = false;
1699 for (GCRelocateInst *ToReplace : Targets) {
1700 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1701 "Not relocating a derived object of the original base object");
1702 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1703 // A duplicate relocate call. TODO: coalesce duplicates.
1707 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1708 // Base and derived relocates are in different basic blocks.
1709 // In this case transform is only valid when base dominates derived
1710 // relocate. However it would be too expensive to check dominance
1711 // for each such relocate, so we skip the whole transformation.
1715 Value *Base = ToReplace->getBasePtr();
1716 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1717 if (!Derived || Derived->getPointerOperand() != Base)
1720 SmallVector<Value *, 2> OffsetV;
1721 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1724 // Create a Builder and replace the target callsite with a gep
1725 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
1727 // Insert after RelocatedBase
1728 IRBuilder<> Builder(RelocatedBase->getNextNode());
1729 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1731 // If gc_relocate does not match the actual type, cast it to the right type.
1732 // In theory, there must be a bitcast after gc_relocate if the type does not
1733 // match, and we should reuse it to get the derived pointer. But it could be
1737 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1742 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1746 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1747 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1749 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1750 // no matter there is already one or not. In this way, we can handle all cases, and
1751 // the extra bitcast should be optimized away in later passes.
1752 Value *ActualRelocatedBase = RelocatedBase;
1753 if (RelocatedBase->getType() != Base->getType()) {
1754 ActualRelocatedBase =
1755 Builder.CreateBitCast(RelocatedBase, Base->getType());
1757 Value *Replacement = Builder.CreateGEP(
1758 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1759 Replacement->takeName(ToReplace);
1760 // If the newly generated derived pointer's type does not match the original derived
1761 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
1762 Value *ActualReplacement = Replacement;
1763 if (Replacement->getType() != ToReplace->getType()) {
1765 Builder.CreateBitCast(Replacement, ToReplace->getType());
1767 ToReplace->replaceAllUsesWith(ActualReplacement);
1768 ToReplace->eraseFromParent();
1778 // %ptr = gep %base + 15
1779 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1780 // %base' = relocate(%tok, i32 4, i32 4)
1781 // %ptr' = relocate(%tok, i32 4, i32 5)
1782 // %val = load %ptr'
1787 // %ptr = gep %base + 15
1788 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1789 // %base' = gc.relocate(%tok, i32 4, i32 4)
1790 // %ptr' = gep %base' + 15
1791 // %val = load %ptr'
1792 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1793 bool MadeChange = false;
1794 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1796 for (auto *U : I.users())
1797 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1798 // Collect all the relocate calls associated with a statepoint
1799 AllRelocateCalls.push_back(Relocate);
1801 // We need atleast one base pointer relocation + one derived pointer
1802 // relocation to mangle
1803 if (AllRelocateCalls.size() < 2)
1806 // RelocateInstMap is a mapping from the base relocate instruction to the
1807 // corresponding derived relocate instructions
1808 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1809 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1810 if (RelocateInstMap.empty())
1813 for (auto &Item : RelocateInstMap)
1814 // Item.first is the RelocatedBase to offset against
1815 // Item.second is the vector of Targets to replace
1816 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1820 /// SinkCast - Sink the specified cast instruction into its user blocks
1821 static bool SinkCast(CastInst *CI) {
1822 BasicBlock *DefBB = CI->getParent();
1824 /// InsertedCasts - Only insert a cast in each block once.
1825 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1827 bool MadeChange = false;
1828 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1830 Use &TheUse = UI.getUse();
1831 Instruction *User = cast<Instruction>(*UI);
1833 // Figure out which BB this cast is used in. For PHI's this is the
1834 // appropriate predecessor block.
1835 BasicBlock *UserBB = User->getParent();
1836 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1837 UserBB = PN->getIncomingBlock(TheUse);
1840 // Preincrement use iterator so we don't invalidate it.
1843 // If the block selected to receive the cast is an EH pad that does not
1844 // allow non-PHI instructions before the terminator, we can't sink the
1846 if (UserBB->getTerminator()->isEHPad())
1849 // If this user is in the same block as the cast, don't change the cast.
1850 if (UserBB == DefBB) continue;
1852 // If we have already inserted a cast into this block, use it.
1853 CastInst *&InsertedCast = InsertedCasts[UserBB];
1855 if (!InsertedCast) {
1856 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1857 assert(InsertPt != UserBB->end());
1858 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1859 CI->getType(), "", &*InsertPt);
1862 // Replace a use of the cast with a use of the new cast.
1863 TheUse = InsertedCast;
1868 // If we removed all uses, nuke the cast.
1869 if (CI->use_empty()) {
1870 CI->eraseFromParent();
1877 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1878 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1879 /// reduce the number of virtual registers that must be created and coalesced.
1881 /// Return true if any changes are made.
1883 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1884 const DataLayout &DL) {
1885 // If this is a noop copy,
1886 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1887 EVT DstVT = TLI.getValueType(DL, CI->getType());
1889 // This is an fp<->int conversion?
1890 if (SrcVT.isInteger() != DstVT.isInteger())
1893 // If this is an extension, it will be a zero or sign extension, which
1895 if (SrcVT.bitsLT(DstVT)) return false;
1897 // If these values will be promoted, find out what they will be promoted
1898 // to. This helps us consider truncates on PPC as noop copies when they
1900 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1901 TargetLowering::TypePromoteInteger)
1902 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1903 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1904 TargetLowering::TypePromoteInteger)
1905 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1907 // If, after promotion, these are the same types, this is a noop copy.
1911 return SinkCast(CI);
1914 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1917 /// Return true if any changes were made.
1918 static bool CombineUAddWithOverflow(CmpInst *CI) {
1922 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1925 Type *Ty = AddI->getType();
1926 if (!isa<IntegerType>(Ty))
1929 // We don't want to move around uses of condition values this late, so we we
1930 // check if it is legal to create the call to the intrinsic in the basic
1931 // block containing the icmp:
1933 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1937 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1939 if (AddI->hasOneUse())
1940 assert(*AddI->user_begin() == CI && "expected!");
1943 Module *M = CI->getModule();
1944 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1946 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1948 auto *UAddWithOverflow =
1949 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1950 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1952 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1954 CI->replaceAllUsesWith(Overflow);
1955 AddI->replaceAllUsesWith(UAdd);
1956 CI->eraseFromParent();
1957 AddI->eraseFromParent();
1961 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1962 /// registers that must be created and coalesced. This is a clear win except on
1963 /// targets with multiple condition code registers (PowerPC), where it might
1964 /// lose; some adjustment may be wanted there.
1966 /// Return true if any changes are made.
1967 static bool SinkCmpExpression(CmpInst *CI) {
1968 BasicBlock *DefBB = CI->getParent();
1970 /// Only insert a cmp in each block once.
1971 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1973 bool MadeChange = false;
1974 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1976 Use &TheUse = UI.getUse();
1977 Instruction *User = cast<Instruction>(*UI);
1979 // Preincrement use iterator so we don't invalidate it.
1982 // Don't bother for PHI nodes.
1983 if (isa<PHINode>(User))
1986 // Figure out which BB this cmp is used in.
1987 BasicBlock *UserBB = User->getParent();
1989 // If this user is in the same block as the cmp, don't change the cmp.
1990 if (UserBB == DefBB) continue;
1992 // If we have already inserted a cmp into this block, use it.
1993 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1996 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1997 assert(InsertPt != UserBB->end());
1999 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
2000 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
2003 // Replace a use of the cmp with a use of the new cmp.
2004 TheUse = InsertedCmp;
2009 // If we removed all uses, nuke the cmp.
2010 if (CI->use_empty()) {
2011 CI->eraseFromParent();
2018 static bool OptimizeCmpExpression(CmpInst *CI) {
2019 if (SinkCmpExpression(CI))
2022 if (CombineUAddWithOverflow(CI))
2028 /// Check if the candidates could be combined with a shift instruction, which
2030 /// 1. Truncate instruction
2031 /// 2. And instruction and the imm is a mask of the low bits:
2032 /// imm & (imm+1) == 0
2033 static bool isExtractBitsCandidateUse(Instruction *User) {
2034 if (!isa<TruncInst>(User)) {
2035 if (User->getOpcode() != Instruction::And ||
2036 !isa<ConstantInt>(User->getOperand(1)))
2039 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2041 if ((Cimm & (Cimm + 1)).getBoolValue())
2047 /// Sink both shift and truncate instruction to the use of truncate's BB.
2049 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
2050 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
2051 const TargetLowering &TLI, const DataLayout &DL) {
2052 BasicBlock *UserBB = User->getParent();
2053 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
2054 TruncInst *TruncI = dyn_cast<TruncInst>(User);
2055 bool MadeChange = false;
2057 for (Value::user_iterator TruncUI = TruncI->user_begin(),
2058 TruncE = TruncI->user_end();
2059 TruncUI != TruncE;) {
2061 Use &TruncTheUse = TruncUI.getUse();
2062 Instruction *TruncUser = cast<Instruction>(*TruncUI);
2063 // Preincrement use iterator so we don't invalidate it.
2067 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2071 // If the use is actually a legal node, there will not be an
2072 // implicit truncate.
2073 // FIXME: always querying the result type is just an
2074 // approximation; some nodes' legality is determined by the
2075 // operand or other means. There's no good way to find out though.
2076 if (TLI.isOperationLegalOrCustom(
2077 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2080 // Don't bother for PHI nodes.
2081 if (isa<PHINode>(TruncUser))
2084 BasicBlock *TruncUserBB = TruncUser->getParent();
2086 if (UserBB == TruncUserBB)
2089 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2090 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2092 if (!InsertedShift && !InsertedTrunc) {
2093 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2094 assert(InsertPt != TruncUserBB->end());
2096 if (ShiftI->getOpcode() == Instruction::AShr)
2097 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2100 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2104 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2106 assert(TruncInsertPt != TruncUserBB->end());
2108 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2109 TruncI->getType(), "", &*TruncInsertPt);
2113 TruncTheUse = InsertedTrunc;
2119 /// Sink the shift *right* instruction into user blocks if the uses could
2120 /// potentially be combined with this shift instruction and generate BitExtract
2121 /// instruction. It will only be applied if the architecture supports BitExtract
2122 /// instruction. Here is an example:
2124 /// %x.extract.shift = lshr i64 %arg1, 32
2126 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2130 /// %x.extract.shift.1 = lshr i64 %arg1, 32
2131 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2133 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
2135 /// Return true if any changes are made.
2136 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
2137 const TargetLowering &TLI,
2138 const DataLayout &DL) {
2139 BasicBlock *DefBB = ShiftI->getParent();
2141 /// Only insert instructions in each block once.
2142 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
2144 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2146 bool MadeChange = false;
2147 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2149 Use &TheUse = UI.getUse();
2150 Instruction *User = cast<Instruction>(*UI);
2151 // Preincrement use iterator so we don't invalidate it.
2154 // Don't bother for PHI nodes.
2155 if (isa<PHINode>(User))
2158 if (!isExtractBitsCandidateUse(User))
2161 BasicBlock *UserBB = User->getParent();
2163 if (UserBB == DefBB) {
2164 // If the shift and truncate instruction are in the same BB. The use of
2165 // the truncate(TruncUse) may still introduce another truncate if not
2166 // legal. In this case, we would like to sink both shift and truncate
2167 // instruction to the BB of TruncUse.
2170 // i64 shift.result = lshr i64 opnd, imm
2171 // trunc.result = trunc shift.result to i16
2174 // ----> We will have an implicit truncate here if the architecture does
2175 // not have i16 compare.
2176 // cmp i16 trunc.result, opnd2
2178 if (isa<TruncInst>(User) && shiftIsLegal
2179 // If the type of the truncate is legal, no trucate will be
2180 // introduced in other basic blocks.
2182 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2184 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2188 // If we have already inserted a shift into this block, use it.
2189 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2191 if (!InsertedShift) {
2192 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2193 assert(InsertPt != UserBB->end());
2195 if (ShiftI->getOpcode() == Instruction::AShr)
2196 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2199 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2205 // Replace a use of the shift with a use of the new shift.
2206 TheUse = InsertedShift;
2209 // If we removed all uses, nuke the shift.
2210 if (ShiftI->use_empty())
2211 ShiftI->eraseFromParent();
2216 // Translate a masked load intrinsic like
2217 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
2218 // <16 x i1> %mask, <16 x i32> %passthru)
2219 // to a chain of basic blocks, with loading element one-by-one if
2220 // the appropriate mask bit is set
2222 // %1 = bitcast i8* %addr to i32*
2223 // %2 = extractelement <16 x i1> %mask, i32 0
2224 // %3 = icmp eq i1 %2, true
2225 // br i1 %3, label %cond.load, label %else
2227 //cond.load: ; preds = %0
2228 // %4 = getelementptr i32* %1, i32 0
2229 // %5 = load i32* %4
2230 // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
2233 //else: ; preds = %0, %cond.load
2234 // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
2235 // %7 = extractelement <16 x i1> %mask, i32 1
2236 // %8 = icmp eq i1 %7, true
2237 // br i1 %8, label %cond.load1, label %else2
2239 //cond.load1: ; preds = %else
2240 // %9 = getelementptr i32* %1, i32 1
2241 // %10 = load i32* %9
2242 // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
2245 //else2: ; preds = %else, %cond.load1
2246 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2247 // %12 = extractelement <16 x i1> %mask, i32 2
2248 // %13 = icmp eq i1 %12, true
2249 // br i1 %13, label %cond.load4, label %else5
2251 static void ScalarizeMaskedLoad(CallInst *CI) {
2252 Value *Ptr = CI->getArgOperand(0);
2253 Value *Alignment = CI->getArgOperand(1);
2254 Value *Mask = CI->getArgOperand(2);
2255 Value *Src0 = CI->getArgOperand(3);
2257 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2258 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2259 assert(VecType && "Unexpected return type of masked load intrinsic");
2261 Type *EltTy = CI->getType()->getVectorElementType();
2263 IRBuilder<> Builder(CI->getContext());
2264 Instruction *InsertPt = CI;
2265 BasicBlock *IfBlock = CI->getParent();
2266 BasicBlock *CondBlock = nullptr;
2267 BasicBlock *PrevIfBlock = CI->getParent();
2269 Builder.SetInsertPoint(InsertPt);
2270 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2272 // Short-cut if the mask is all-true.
2273 bool IsAllOnesMask = isa<Constant>(Mask) &&
2274 cast<Constant>(Mask)->isAllOnesValue();
2276 if (IsAllOnesMask) {
2277 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
2278 CI->replaceAllUsesWith(NewI);
2279 CI->eraseFromParent();
2283 // Adjust alignment for the scalar instruction.
2284 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
2285 // Bitcast %addr fron i8* to EltTy*
2287 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2288 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2289 unsigned VectorWidth = VecType->getNumElements();
2291 Value *UndefVal = UndefValue::get(VecType);
2293 // The result vector
2294 Value *VResult = UndefVal;
2296 if (isa<ConstantVector>(Mask)) {
2297 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2298 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2301 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2302 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2303 VResult = Builder.CreateInsertElement(VResult, Load,
2304 Builder.getInt32(Idx));
2306 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2307 CI->replaceAllUsesWith(NewI);
2308 CI->eraseFromParent();
2312 PHINode *Phi = nullptr;
2313 Value *PrevPhi = UndefVal;
2315 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2317 // Fill the "else" block, created in the previous iteration
2319 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2320 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2321 // %to_load = icmp eq i1 %mask_1, true
2322 // br i1 %to_load, label %cond.load, label %else
2325 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2326 Phi->addIncoming(VResult, CondBlock);
2327 Phi->addIncoming(PrevPhi, PrevIfBlock);
2332 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2333 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2334 ConstantInt::get(Predicate->getType(), 1));
2336 // Create "cond" block
2338 // %EltAddr = getelementptr i32* %1, i32 0
2339 // %Elt = load i32* %EltAddr
2340 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2342 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
2343 Builder.SetInsertPoint(InsertPt);
2346 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2347 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2348 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
2350 // Create "else" block, fill it in the next iteration
2351 BasicBlock *NewIfBlock =
2352 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2353 Builder.SetInsertPoint(InsertPt);
2354 Instruction *OldBr = IfBlock->getTerminator();
2355 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2356 OldBr->eraseFromParent();
2357 PrevIfBlock = IfBlock;
2358 IfBlock = NewIfBlock;
2361 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2362 Phi->addIncoming(VResult, CondBlock);
2363 Phi->addIncoming(PrevPhi, PrevIfBlock);
2364 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2365 CI->replaceAllUsesWith(NewI);
2366 CI->eraseFromParent();
2369 // Translate a masked store intrinsic, like
2370 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
2372 // to a chain of basic blocks, that stores element one-by-one if
2373 // the appropriate mask bit is set
2375 // %1 = bitcast i8* %addr to i32*
2376 // %2 = extractelement <16 x i1> %mask, i32 0
2377 // %3 = icmp eq i1 %2, true
2378 // br i1 %3, label %cond.store, label %else
2380 // cond.store: ; preds = %0
2381 // %4 = extractelement <16 x i32> %val, i32 0
2382 // %5 = getelementptr i32* %1, i32 0
2383 // store i32 %4, i32* %5
2386 // else: ; preds = %0, %cond.store
2387 // %6 = extractelement <16 x i1> %mask, i32 1
2388 // %7 = icmp eq i1 %6, true
2389 // br i1 %7, label %cond.store1, label %else2
2391 // cond.store1: ; preds = %else
2392 // %8 = extractelement <16 x i32> %val, i32 1
2393 // %9 = getelementptr i32* %1, i32 1
2394 // store i32 %8, i32* %9
2397 static void ScalarizeMaskedStore(CallInst *CI) {
2398 Value *Src = CI->getArgOperand(0);
2399 Value *Ptr = CI->getArgOperand(1);
2400 Value *Alignment = CI->getArgOperand(2);
2401 Value *Mask = CI->getArgOperand(3);
2403 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2404 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
2405 assert(VecType && "Unexpected data type in masked store intrinsic");
2407 Type *EltTy = VecType->getElementType();
2409 IRBuilder<> Builder(CI->getContext());
2410 Instruction *InsertPt = CI;
2411 BasicBlock *IfBlock = CI->getParent();
2412 Builder.SetInsertPoint(InsertPt);
2413 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2415 // Short-cut if the mask is all-true.
2416 bool IsAllOnesMask = isa<Constant>(Mask) &&
2417 cast<Constant>(Mask)->isAllOnesValue();
2419 if (IsAllOnesMask) {
2420 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
2421 CI->eraseFromParent();
2425 // Adjust alignment for the scalar instruction.
2426 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
2427 // Bitcast %addr fron i8* to EltTy*
2429 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2430 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2431 unsigned VectorWidth = VecType->getNumElements();
2433 if (isa<ConstantVector>(Mask)) {
2434 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2435 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2437 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2439 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2440 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2442 CI->eraseFromParent();
2446 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2448 // Fill the "else" block, created in the previous iteration
2450 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2451 // %to_store = icmp eq i1 %mask_1, true
2452 // br i1 %to_store, label %cond.store, label %else
2454 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2455 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2456 ConstantInt::get(Predicate->getType(), 1));
2458 // Create "cond" block
2460 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
2461 // %EltAddr = getelementptr i32* %1, i32 0
2462 // %store i32 %OneElt, i32* %EltAddr
2464 BasicBlock *CondBlock =
2465 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
2466 Builder.SetInsertPoint(InsertPt);
2468 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2470 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2471 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2473 // Create "else" block, fill it in the next iteration
2474 BasicBlock *NewIfBlock =
2475 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2476 Builder.SetInsertPoint(InsertPt);
2477 Instruction *OldBr = IfBlock->getTerminator();
2478 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2479 OldBr->eraseFromParent();
2480 IfBlock = NewIfBlock;
2482 CI->eraseFromParent();
2485 // Translate a masked gather intrinsic like
2486 // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
2487 // <16 x i1> %Mask, <16 x i32> %Src)
2488 // to a chain of basic blocks, with loading element one-by-one if
2489 // the appropriate mask bit is set
2491 // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
2492 // % Mask0 = extractelement <16 x i1> %Mask, i32 0
2493 // % ToLoad0 = icmp eq i1 % Mask0, true
2494 // br i1 % ToLoad0, label %cond.load, label %else
2497 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2498 // % Load0 = load i32, i32* % Ptr0, align 4
2499 // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
2503 // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
2504 // % Mask1 = extractelement <16 x i1> %Mask, i32 1
2505 // % ToLoad1 = icmp eq i1 % Mask1, true
2506 // br i1 % ToLoad1, label %cond.load1, label %else2
2509 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2510 // % Load1 = load i32, i32* % Ptr1, align 4
2511 // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
2514 // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
2515 // ret <16 x i32> %Result
2516 static void ScalarizeMaskedGather(CallInst *CI) {
2517 Value *Ptrs = CI->getArgOperand(0);
2518 Value *Alignment = CI->getArgOperand(1);
2519 Value *Mask = CI->getArgOperand(2);
2520 Value *Src0 = CI->getArgOperand(3);
2522 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2524 assert(VecType && "Unexpected return type of masked load intrinsic");
2526 IRBuilder<> Builder(CI->getContext());
2527 Instruction *InsertPt = CI;
2528 BasicBlock *IfBlock = CI->getParent();
2529 BasicBlock *CondBlock = nullptr;
2530 BasicBlock *PrevIfBlock = CI->getParent();
2531 Builder.SetInsertPoint(InsertPt);
2532 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2534 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2536 Value *UndefVal = UndefValue::get(VecType);
2538 // The result vector
2539 Value *VResult = UndefVal;
2540 unsigned VectorWidth = VecType->getNumElements();
2542 // Shorten the way if the mask is a vector of constants.
2543 bool IsConstMask = isa<ConstantVector>(Mask);
2546 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2547 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2549 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2550 "Ptr" + Twine(Idx));
2551 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2552 "Load" + Twine(Idx));
2553 VResult = Builder.CreateInsertElement(VResult, Load,
2554 Builder.getInt32(Idx),
2555 "Res" + Twine(Idx));
2557 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2558 CI->replaceAllUsesWith(NewI);
2559 CI->eraseFromParent();
2563 PHINode *Phi = nullptr;
2564 Value *PrevPhi = UndefVal;
2566 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2568 // Fill the "else" block, created in the previous iteration
2570 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
2571 // %ToLoad1 = icmp eq i1 %Mask1, true
2572 // br i1 %ToLoad1, label %cond.load, label %else
2575 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2576 Phi->addIncoming(VResult, CondBlock);
2577 Phi->addIncoming(PrevPhi, PrevIfBlock);
2582 Value *Predicate = Builder.CreateExtractElement(Mask,
2583 Builder.getInt32(Idx),
2584 "Mask" + Twine(Idx));
2585 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2586 ConstantInt::get(Predicate->getType(), 1),
2587 "ToLoad" + Twine(Idx));
2589 // Create "cond" block
2591 // %EltAddr = getelementptr i32* %1, i32 0
2592 // %Elt = load i32* %EltAddr
2593 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2595 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
2596 Builder.SetInsertPoint(InsertPt);
2598 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2599 "Ptr" + Twine(Idx));
2600 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2601 "Load" + Twine(Idx));
2602 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
2603 "Res" + Twine(Idx));
2605 // Create "else" block, fill it in the next iteration
2606 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2607 Builder.SetInsertPoint(InsertPt);
2608 Instruction *OldBr = IfBlock->getTerminator();
2609 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2610 OldBr->eraseFromParent();
2611 PrevIfBlock = IfBlock;
2612 IfBlock = NewIfBlock;
2615 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2616 Phi->addIncoming(VResult, CondBlock);
2617 Phi->addIncoming(PrevPhi, PrevIfBlock);
2618 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2619 CI->replaceAllUsesWith(NewI);
2620 CI->eraseFromParent();
2623 // Translate a masked scatter intrinsic, like
2624 // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
2626 // to a chain of basic blocks, that stores element one-by-one if
2627 // the appropriate mask bit is set.
2629 // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
2630 // % Mask0 = extractelement <16 x i1> % Mask, i32 0
2631 // % ToStore0 = icmp eq i1 % Mask0, true
2632 // br i1 %ToStore0, label %cond.store, label %else
2635 // % Elt0 = extractelement <16 x i32> %Src, i32 0
2636 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2637 // store i32 %Elt0, i32* % Ptr0, align 4
2641 // % Mask1 = extractelement <16 x i1> % Mask, i32 1
2642 // % ToStore1 = icmp eq i1 % Mask1, true
2643 // br i1 % ToStore1, label %cond.store1, label %else2
2646 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2647 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2648 // store i32 % Elt1, i32* % Ptr1, align 4
2651 static void ScalarizeMaskedScatter(CallInst *CI) {
2652 Value *Src = CI->getArgOperand(0);
2653 Value *Ptrs = CI->getArgOperand(1);
2654 Value *Alignment = CI->getArgOperand(2);
2655 Value *Mask = CI->getArgOperand(3);
2657 assert(isa<VectorType>(Src->getType()) &&
2658 "Unexpected data type in masked scatter intrinsic");
2659 assert(isa<VectorType>(Ptrs->getType()) &&
2660 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
2661 "Vector of pointers is expected in masked scatter intrinsic");
2663 IRBuilder<> Builder(CI->getContext());
2664 Instruction *InsertPt = CI;
2665 BasicBlock *IfBlock = CI->getParent();
2666 Builder.SetInsertPoint(InsertPt);
2667 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2669 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2670 unsigned VectorWidth = Src->getType()->getVectorNumElements();
2672 // Shorten the way if the mask is a vector of constants.
2673 bool IsConstMask = isa<ConstantVector>(Mask);
2676 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2677 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2679 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2680 "Elt" + Twine(Idx));
2681 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2682 "Ptr" + Twine(Idx));
2683 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2685 CI->eraseFromParent();
2688 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2689 // Fill the "else" block, created in the previous iteration
2691 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
2692 // % ToStore = icmp eq i1 % Mask1, true
2693 // br i1 % ToStore, label %cond.store, label %else
2695 Value *Predicate = Builder.CreateExtractElement(Mask,
2696 Builder.getInt32(Idx),
2697 "Mask" + Twine(Idx));
2699 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2700 ConstantInt::get(Predicate->getType(), 1),
2701 "ToStore" + Twine(Idx));
2703 // Create "cond" block
2705 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2706 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2707 // %store i32 % Elt1, i32* % Ptr1
2709 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2710 Builder.SetInsertPoint(InsertPt);
2712 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2713 "Elt" + Twine(Idx));
2714 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2715 "Ptr" + Twine(Idx));
2716 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2718 // Create "else" block, fill it in the next iteration
2719 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2720 Builder.SetInsertPoint(InsertPt);
2721 Instruction *OldBr = IfBlock->getTerminator();
2722 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2723 OldBr->eraseFromParent();
2724 IfBlock = NewIfBlock;
2726 CI->eraseFromParent();
2729 /// If counting leading or trailing zeros is an expensive operation and a zero
2730 /// input is defined, add a check for zero to avoid calling the intrinsic.
2732 /// We want to transform:
2733 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2737 /// %cmpz = icmp eq i64 %A, 0
2738 /// br i1 %cmpz, label %cond.end, label %cond.false
2740 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2741 /// br label %cond.end
2743 /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2745 /// If the transform is performed, return true and set ModifiedDT to true.
2746 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2747 const TargetLowering *TLI,
2748 const DataLayout *DL,
2753 // If a zero input is undefined, it doesn't make sense to despeculate that.
2754 if (match(CountZeros->getOperand(1), m_One()))
2757 // If it's cheap to speculate, there's nothing to do.
2758 auto IntrinsicID = CountZeros->getIntrinsicID();
2759 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2760 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2763 // Only handle legal scalar cases. Anything else requires too much work.
2764 Type *Ty = CountZeros->getType();
2765 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
2766 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
2769 // The intrinsic will be sunk behind a compare against zero and branch.
2770 BasicBlock *StartBlock = CountZeros->getParent();
2771 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2773 // Create another block after the count zero intrinsic. A PHI will be added
2774 // in this block to select the result of the intrinsic or the bit-width
2775 // constant if the input to the intrinsic is zero.
2776 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2777 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2779 // Set up a builder to create a compare, conditional branch, and PHI.
2780 IRBuilder<> Builder(CountZeros->getContext());
2781 Builder.SetInsertPoint(StartBlock->getTerminator());
2782 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2784 // Replace the unconditional branch that was created by the first split with
2785 // a compare against zero and a conditional branch.
2786 Value *Zero = Constant::getNullValue(Ty);
2787 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2788 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2789 StartBlock->getTerminator()->eraseFromParent();
2791 // Create a PHI in the end block to select either the output of the intrinsic
2792 // or the bit width of the operand.
2793 Builder.SetInsertPoint(&EndBlock->front());
2794 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2795 CountZeros->replaceAllUsesWith(PN);
2796 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2797 PN->addIncoming(BitWidth, StartBlock);
2798 PN->addIncoming(CountZeros, CallBlock);
2800 // We are explicitly handling the zero case, so we can set the intrinsic's
2801 // undefined zero argument to 'true'. This will also prevent reprocessing the
2802 // intrinsic; we only despeculate when a zero input is defined.
2803 CountZeros->setArgOperand(1, Builder.getTrue());
2808 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
2809 BasicBlock *BB = CI->getParent();
2811 // Lower inline assembly if we can.
2812 // If we found an inline asm expession, and if the target knows how to
2813 // lower it to normal LLVM code, do so now.
2814 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2815 if (TLI->ExpandInlineAsm(CI)) {
2816 // Avoid invalidating the iterator.
2817 CurInstIterator = BB->begin();
2818 // Avoid processing instructions out of order, which could cause
2819 // reuse before a value is defined.
2823 // Sink address computing for memory operands into the block.
2824 if (optimizeInlineAsmInst(CI))
2828 // Align the pointer arguments to this call if the target thinks it's a good
2830 unsigned MinSize, PrefAlign;
2831 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2832 for (auto &Arg : CI->arg_operands()) {
2833 // We want to align both objects whose address is used directly and
2834 // objects whose address is used in casts and GEPs, though it only makes
2835 // sense for GEPs if the offset is a multiple of the desired alignment and
2836 // if size - offset meets the size threshold.
2837 if (!Arg->getType()->isPointerTy())
2839 APInt Offset(DL->getPointerSizeInBits(
2840 cast<PointerType>(Arg->getType())->getAddressSpace()),
2842 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2843 uint64_t Offset2 = Offset.getLimitedValue();
2844 if ((Offset2 & (PrefAlign-1)) != 0)
2847 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2848 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2849 AI->setAlignment(PrefAlign);
2850 // Global variables can only be aligned if they are defined in this
2851 // object (i.e. they are uniquely initialized in this object), and
2852 // over-aligning global variables that have an explicit section is
2855 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2856 GV->getAlignment() < PrefAlign &&
2857 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
2859 GV->setAlignment(PrefAlign);
2861 // If this is a memcpy (or similar) then we may be able to improve the
2863 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2864 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2865 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2866 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2867 if (Align > MI->getAlignment())
2868 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2872 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2874 switch (II->getIntrinsicID()) {
2876 case Intrinsic::objectsize: {
2877 // Lower all uses of llvm.objectsize.*
2878 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
2879 Type *ReturnTy = CI->getType();
2880 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
2882 // Substituting this can cause recursive simplifications, which can
2883 // invalidate our iterator. Use a WeakVH to hold onto it in case this
2885 WeakVH IterHandle(&*CurInstIterator);
2887 replaceAndRecursivelySimplify(CI, RetVal,
2890 // If the iterator instruction was recursively deleted, start over at the
2891 // start of the block.
2892 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
2893 CurInstIterator = BB->begin();
2898 case Intrinsic::masked_load: {
2899 // Scalarize unsupported vector masked load
2900 if (!TTI->isLegalMaskedLoad(CI->getType())) {
2901 ScalarizeMaskedLoad(CI);
2907 case Intrinsic::masked_store: {
2908 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
2909 ScalarizeMaskedStore(CI);
2915 case Intrinsic::masked_gather: {
2916 if (!TTI->isLegalMaskedGather(CI->getType())) {
2917 ScalarizeMaskedGather(CI);
2923 case Intrinsic::masked_scatter: {
2924 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
2925 ScalarizeMaskedScatter(CI);
2931 case Intrinsic::aarch64_stlxr:
2932 case Intrinsic::aarch64_stxr: {
2933 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2934 if (!ExtVal || !ExtVal->hasOneUse() ||
2935 ExtVal->getParent() == CI->getParent())
2937 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2938 ExtVal->moveBefore(CI);
2939 // Mark this instruction as "inserted by CGP", so that other
2940 // optimizations don't touch it.
2941 InsertedInsts.insert(ExtVal);
2944 case Intrinsic::invariant_group_barrier:
2945 II->replaceAllUsesWith(II->getArgOperand(0));
2946 II->eraseFromParent();
2949 case Intrinsic::cttz:
2950 case Intrinsic::ctlz:
2951 // If counting zeros is expensive, try to avoid it.
2952 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2956 // Unknown address space.
2957 // TODO: Target hook to pick which address space the intrinsic cares
2959 unsigned AddrSpace = ~0u;
2960 SmallVector<Value*, 2> PtrOps;
2962 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
2963 while (!PtrOps.empty())
2964 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
2969 // From here on out we're working with named functions.
2970 if (!CI->getCalledFunction()) return false;
2972 // Lower all default uses of _chk calls. This is very similar
2973 // to what InstCombineCalls does, but here we are only lowering calls
2974 // to fortified library functions (e.g. __memcpy_chk) that have the default
2975 // "don't know" as the objectsize. Anything else should be left alone.
2976 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2977 if (Value *V = Simplifier.optimizeCall(CI)) {
2978 CI->replaceAllUsesWith(V);
2979 CI->eraseFromParent();
2985 /// Look for opportunities to duplicate return instructions to the predecessor
2986 /// to enable tail call optimizations. The case it is currently looking for is:
2989 /// %tmp0 = tail call i32 @f0()
2990 /// br label %return
2992 /// %tmp1 = tail call i32 @f1()
2993 /// br label %return
2995 /// %tmp2 = tail call i32 @f2()
2996 /// br label %return
2998 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
3006 /// %tmp0 = tail call i32 @f0()
3009 /// %tmp1 = tail call i32 @f1()
3012 /// %tmp2 = tail call i32 @f2()
3015 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
3019 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
3023 PHINode *PN = nullptr;
3024 BitCastInst *BCI = nullptr;
3025 Value *V = RI->getReturnValue();
3027 BCI = dyn_cast<BitCastInst>(V);
3029 V = BCI->getOperand(0);
3031 PN = dyn_cast<PHINode>(V);
3036 if (PN && PN->getParent() != BB)
3039 // It's not safe to eliminate the sign / zero extension of the return value.
3040 // See llvm::isInTailCallPosition().
3041 const Function *F = BB->getParent();
3042 AttributeSet CallerAttrs = F->getAttributes();
3043 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
3044 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
3047 // Make sure there are no instructions between the PHI and return, or that the
3048 // return is the first instruction in the block.
3050 BasicBlock::iterator BI = BB->begin();
3051 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
3053 // Also skip over the bitcast.
3058 BasicBlock::iterator BI = BB->begin();
3059 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
3064 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
3066 SmallVector<CallInst*, 4> TailCalls;
3068 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
3069 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
3070 // Make sure the phi value is indeed produced by the tail call.
3071 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
3072 TLI->mayBeEmittedAsTailCall(CI))
3073 TailCalls.push_back(CI);
3076 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
3077 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
3078 if (!VisitedBBs.insert(*PI).second)
3081 BasicBlock::InstListType &InstList = (*PI)->getInstList();
3082 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
3083 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
3084 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
3088 CallInst *CI = dyn_cast<CallInst>(&*RI);
3089 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
3090 TailCalls.push_back(CI);
3094 bool Changed = false;
3095 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
3096 CallInst *CI = TailCalls[i];
3099 // Conservatively require the attributes of the call to match those of the
3100 // return. Ignore noalias because it doesn't affect the call sequence.
3101 AttributeSet CalleeAttrs = CS.getAttributes();
3102 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
3103 removeAttribute(Attribute::NoAlias) !=
3104 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
3105 removeAttribute(Attribute::NoAlias))
3108 // Make sure the call instruction is followed by an unconditional branch to
3109 // the return block.
3110 BasicBlock *CallBB = CI->getParent();
3111 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
3112 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
3115 // Duplicate the return into CallBB.
3116 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
3117 ModifiedDT = Changed = true;
3121 // If we eliminated all predecessors of the block, delete the block now.
3122 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
3123 BB->eraseFromParent();
3128 //===----------------------------------------------------------------------===//
3129 // Memory Optimization
3130 //===----------------------------------------------------------------------===//
3134 /// This is an extended version of TargetLowering::AddrMode
3135 /// which holds actual Value*'s for register values.
3136 struct ExtAddrMode : public TargetLowering::AddrMode {
3139 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
3140 void print(raw_ostream &OS) const;
3143 bool operator==(const ExtAddrMode& O) const {
3144 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
3145 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
3146 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
3151 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3157 void ExtAddrMode::print(raw_ostream &OS) const {
3158 bool NeedPlus = false;
3161 OS << (NeedPlus ? " + " : "")
3163 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3168 OS << (NeedPlus ? " + " : "")
3174 OS << (NeedPlus ? " + " : "")
3176 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3180 OS << (NeedPlus ? " + " : "")
3182 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3188 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3189 void ExtAddrMode::dump() const {
3195 /// \brief This class provides transaction based operation on the IR.
3196 /// Every change made through this class is recorded in the internal state and
3197 /// can be undone (rollback) until commit is called.
3198 class TypePromotionTransaction {
3200 /// \brief This represents the common interface of the individual transaction.
3201 /// Each class implements the logic for doing one specific modification on
3202 /// the IR via the TypePromotionTransaction.
3203 class TypePromotionAction {
3205 /// The Instruction modified.
3209 /// \brief Constructor of the action.
3210 /// The constructor performs the related action on the IR.
3211 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3213 virtual ~TypePromotionAction() {}
3215 /// \brief Undo the modification done by this action.
3216 /// When this method is called, the IR must be in the same state as it was
3217 /// before this action was applied.
3218 /// \pre Undoing the action works if and only if the IR is in the exact same
3219 /// state as it was directly after this action was applied.
3220 virtual void undo() = 0;
3222 /// \brief Advocate every change made by this action.
3223 /// When the results on the IR of the action are to be kept, it is important
3224 /// to call this function, otherwise hidden information may be kept forever.
3225 virtual void commit() {
3226 // Nothing to be done, this action is not doing anything.
3230 /// \brief Utility to remember the position of an instruction.
3231 class InsertionHandler {
3232 /// Position of an instruction.
3233 /// Either an instruction:
3234 /// - Is the first in a basic block: BB is used.
3235 /// - Has a previous instructon: PrevInst is used.
3237 Instruction *PrevInst;
3240 /// Remember whether or not the instruction had a previous instruction.
3241 bool HasPrevInstruction;
3244 /// \brief Record the position of \p Inst.
3245 InsertionHandler(Instruction *Inst) {
3246 BasicBlock::iterator It = Inst->getIterator();
3247 HasPrevInstruction = (It != (Inst->getParent()->begin()));
3248 if (HasPrevInstruction)
3249 Point.PrevInst = &*--It;
3251 Point.BB = Inst->getParent();
3254 /// \brief Insert \p Inst at the recorded position.
3255 void insert(Instruction *Inst) {
3256 if (HasPrevInstruction) {
3257 if (Inst->getParent())
3258 Inst->removeFromParent();
3259 Inst->insertAfter(Point.PrevInst);
3261 Instruction *Position = &*Point.BB->getFirstInsertionPt();
3262 if (Inst->getParent())
3263 Inst->moveBefore(Position);
3265 Inst->insertBefore(Position);
3270 /// \brief Move an instruction before another.
3271 class InstructionMoveBefore : public TypePromotionAction {
3272 /// Original position of the instruction.
3273 InsertionHandler Position;
3276 /// \brief Move \p Inst before \p Before.
3277 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
3278 : TypePromotionAction(Inst), Position(Inst) {
3279 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
3280 Inst->moveBefore(Before);
3283 /// \brief Move the instruction back to its original position.
3284 void undo() override {
3285 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3286 Position.insert(Inst);
3290 /// \brief Set the operand of an instruction with a new value.
3291 class OperandSetter : public TypePromotionAction {
3292 /// Original operand of the instruction.
3294 /// Index of the modified instruction.
3298 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
3299 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3300 : TypePromotionAction(Inst), Idx(Idx) {
3301 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3302 << "for:" << *Inst << "\n"
3303 << "with:" << *NewVal << "\n");
3304 Origin = Inst->getOperand(Idx);
3305 Inst->setOperand(Idx, NewVal);
3308 /// \brief Restore the original value of the instruction.
3309 void undo() override {
3310 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3311 << "for: " << *Inst << "\n"
3312 << "with: " << *Origin << "\n");
3313 Inst->setOperand(Idx, Origin);
3317 /// \brief Hide the operands of an instruction.
3318 /// Do as if this instruction was not using any of its operands.
3319 class OperandsHider : public TypePromotionAction {
3320 /// The list of original operands.
3321 SmallVector<Value *, 4> OriginalValues;
3324 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
3325 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3326 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3327 unsigned NumOpnds = Inst->getNumOperands();
3328 OriginalValues.reserve(NumOpnds);
3329 for (unsigned It = 0; It < NumOpnds; ++It) {
3330 // Save the current operand.
3331 Value *Val = Inst->getOperand(It);
3332 OriginalValues.push_back(Val);
3334 // We could use OperandSetter here, but that would imply an overhead
3335 // that we are not willing to pay.
3336 Inst->setOperand(It, UndefValue::get(Val->getType()));
3340 /// \brief Restore the original list of uses.
3341 void undo() override {
3342 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3343 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3344 Inst->setOperand(It, OriginalValues[It]);
3348 /// \brief Build a truncate instruction.
3349 class TruncBuilder : public TypePromotionAction {
3352 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
3354 /// trunc Opnd to Ty.
3355 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3356 IRBuilder<> Builder(Opnd);
3357 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3358 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3361 /// \brief Get the built value.
3362 Value *getBuiltValue() { return Val; }
3364 /// \brief Remove the built instruction.
3365 void undo() override {
3366 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3367 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3368 IVal->eraseFromParent();
3372 /// \brief Build a sign extension instruction.
3373 class SExtBuilder : public TypePromotionAction {
3376 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
3378 /// sext Opnd to Ty.
3379 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3380 : TypePromotionAction(InsertPt) {
3381 IRBuilder<> Builder(InsertPt);
3382 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3383 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3386 /// \brief Get the built value.
3387 Value *getBuiltValue() { return Val; }
3389 /// \brief Remove the built instruction.
3390 void undo() override {
3391 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3392 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3393 IVal->eraseFromParent();
3397 /// \brief Build a zero extension instruction.
3398 class ZExtBuilder : public TypePromotionAction {
3401 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
3403 /// zext Opnd to Ty.
3404 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3405 : TypePromotionAction(InsertPt) {
3406 IRBuilder<> Builder(InsertPt);
3407 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3408 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3411 /// \brief Get the built value.
3412 Value *getBuiltValue() { return Val; }
3414 /// \brief Remove the built instruction.
3415 void undo() override {
3416 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3417 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3418 IVal->eraseFromParent();
3422 /// \brief Mutate an instruction to another type.
3423 class TypeMutator : public TypePromotionAction {
3424 /// Record the original type.
3428 /// \brief Mutate the type of \p Inst into \p NewTy.
3429 TypeMutator(Instruction *Inst, Type *NewTy)
3430 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3431 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3433 Inst->mutateType(NewTy);
3436 /// \brief Mutate the instruction back to its original type.
3437 void undo() override {
3438 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3440 Inst->mutateType(OrigTy);
3444 /// \brief Replace the uses of an instruction by another instruction.
3445 class UsesReplacer : public TypePromotionAction {
3446 /// Helper structure to keep track of the replaced uses.
3447 struct InstructionAndIdx {
3448 /// The instruction using the instruction.
3450 /// The index where this instruction is used for Inst.
3452 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3453 : Inst(Inst), Idx(Idx) {}
3456 /// Keep track of the original uses (pair Instruction, Index).
3457 SmallVector<InstructionAndIdx, 4> OriginalUses;
3458 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
3461 /// \brief Replace all the use of \p Inst by \p New.
3462 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
3463 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3465 // Record the original uses.
3466 for (Use &U : Inst->uses()) {
3467 Instruction *UserI = cast<Instruction>(U.getUser());
3468 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3470 // Now, we can replace the uses.
3471 Inst->replaceAllUsesWith(New);
3474 /// \brief Reassign the original uses of Inst to Inst.
3475 void undo() override {
3476 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3477 for (use_iterator UseIt = OriginalUses.begin(),
3478 EndIt = OriginalUses.end();
3479 UseIt != EndIt; ++UseIt) {
3480 UseIt->Inst->setOperand(UseIt->Idx, Inst);
3485 /// \brief Remove an instruction from the IR.
3486 class InstructionRemover : public TypePromotionAction {
3487 /// Original position of the instruction.
3488 InsertionHandler Inserter;
3489 /// Helper structure to hide all the link to the instruction. In other
3490 /// words, this helps to do as if the instruction was removed.
3491 OperandsHider Hider;
3492 /// Keep track of the uses replaced, if any.
3493 UsesReplacer *Replacer;
3496 /// \brief Remove all reference of \p Inst and optinally replace all its
3498 /// \pre If !Inst->use_empty(), then New != nullptr
3499 InstructionRemover(Instruction *Inst, Value *New = nullptr)
3500 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3503 Replacer = new UsesReplacer(Inst, New);
3504 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3505 Inst->removeFromParent();
3508 ~InstructionRemover() override { delete Replacer; }
3510 /// \brief Really remove the instruction.
3511 void commit() override { delete Inst; }
3513 /// \brief Resurrect the instruction and reassign it to the proper uses if
3514 /// new value was provided when build this action.
3515 void undo() override {
3516 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3517 Inserter.insert(Inst);
3525 /// Restoration point.
3526 /// The restoration point is a pointer to an action instead of an iterator
3527 /// because the iterator may be invalidated but not the pointer.
3528 typedef const TypePromotionAction *ConstRestorationPt;
3529 /// Advocate every changes made in that transaction.
3531 /// Undo all the changes made after the given point.
3532 void rollback(ConstRestorationPt Point);
3533 /// Get the current restoration point.
3534 ConstRestorationPt getRestorationPoint() const;
3536 /// \name API for IR modification with state keeping to support rollback.
3538 /// Same as Instruction::setOperand.
3539 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3540 /// Same as Instruction::eraseFromParent.
3541 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3542 /// Same as Value::replaceAllUsesWith.
3543 void replaceAllUsesWith(Instruction *Inst, Value *New);
3544 /// Same as Value::mutateType.
3545 void mutateType(Instruction *Inst, Type *NewTy);
3546 /// Same as IRBuilder::createTrunc.
3547 Value *createTrunc(Instruction *Opnd, Type *Ty);
3548 /// Same as IRBuilder::createSExt.
3549 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3550 /// Same as IRBuilder::createZExt.
3551 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3552 /// Same as Instruction::moveBefore.
3553 void moveBefore(Instruction *Inst, Instruction *Before);
3557 /// The ordered list of actions made so far.
3558 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3559 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
3562 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3565 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
3568 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3571 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
3574 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3576 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3579 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3580 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3583 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3585 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3586 Value *Val = Ptr->getBuiltValue();
3587 Actions.push_back(std::move(Ptr));
3591 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3592 Value *Opnd, Type *Ty) {
3593 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3594 Value *Val = Ptr->getBuiltValue();
3595 Actions.push_back(std::move(Ptr));
3599 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3600 Value *Opnd, Type *Ty) {
3601 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3602 Value *Val = Ptr->getBuiltValue();
3603 Actions.push_back(std::move(Ptr));
3607 void TypePromotionTransaction::moveBefore(Instruction *Inst,
3608 Instruction *Before) {
3610 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
3613 TypePromotionTransaction::ConstRestorationPt
3614 TypePromotionTransaction::getRestorationPoint() const {
3615 return !Actions.empty() ? Actions.back().get() : nullptr;
3618 void TypePromotionTransaction::commit() {
3619 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
3625 void TypePromotionTransaction::rollback(
3626 TypePromotionTransaction::ConstRestorationPt Point) {
3627 while (!Actions.empty() && Point != Actions.back().get()) {
3628 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3633 /// \brief A helper class for matching addressing modes.
3635 /// This encapsulates the logic for matching the target-legal addressing modes.
3636 class AddressingModeMatcher {
3637 SmallVectorImpl<Instruction*> &AddrModeInsts;
3638 const TargetMachine &TM;
3639 const TargetLowering &TLI;
3640 const DataLayout &DL;
3642 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3643 /// the memory instruction that we're computing this address for.
3646 Instruction *MemoryInst;
3648 /// This is the addressing mode that we're building up. This is
3649 /// part of the return value of this addressing mode matching stuff.
3650 ExtAddrMode &AddrMode;
3652 /// The instructions inserted by other CodeGenPrepare optimizations.
3653 const SetOfInstrs &InsertedInsts;
3654 /// A map from the instructions to their type before promotion.
3655 InstrToOrigTy &PromotedInsts;
3656 /// The ongoing transaction where every action should be registered.
3657 TypePromotionTransaction &TPT;
3659 /// This is set to true when we should not do profitability checks.
3660 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3661 bool IgnoreProfitability;
3663 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
3664 const TargetMachine &TM, Type *AT, unsigned AS,
3665 Instruction *MI, ExtAddrMode &AM,
3666 const SetOfInstrs &InsertedInsts,
3667 InstrToOrigTy &PromotedInsts,
3668 TypePromotionTransaction &TPT)
3669 : AddrModeInsts(AMI), TM(TM),
3670 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
3671 ->getTargetLowering()),
3672 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3673 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3674 PromotedInsts(PromotedInsts), TPT(TPT) {
3675 IgnoreProfitability = false;
3679 /// Find the maximal addressing mode that a load/store of V can fold,
3680 /// give an access type of AccessTy. This returns a list of involved
3681 /// instructions in AddrModeInsts.
3682 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3684 /// \p PromotedInsts maps the instructions to their type before promotion.
3685 /// \p The ongoing transaction where every action should be registered.
3686 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
3687 Instruction *MemoryInst,
3688 SmallVectorImpl<Instruction*> &AddrModeInsts,
3689 const TargetMachine &TM,
3690 const SetOfInstrs &InsertedInsts,
3691 InstrToOrigTy &PromotedInsts,
3692 TypePromotionTransaction &TPT) {
3695 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
3696 MemoryInst, Result, InsertedInsts,
3697 PromotedInsts, TPT).matchAddr(V, 0);
3698 (void)Success; assert(Success && "Couldn't select *anything*?");
3702 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3703 bool matchAddr(Value *V, unsigned Depth);
3704 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
3705 bool *MovedAway = nullptr);
3706 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3707 ExtAddrMode &AMBefore,
3708 ExtAddrMode &AMAfter);
3709 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3710 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3711 Value *PromotedOperand) const;
3714 /// Try adding ScaleReg*Scale to the current addressing mode.
3715 /// Return true and update AddrMode if this addr mode is legal for the target,
3717 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3719 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3720 // mode. Just process that directly.
3722 return matchAddr(ScaleReg, Depth);
3724 // If the scale is 0, it takes nothing to add this.
3728 // If we already have a scale of this value, we can add to it, otherwise, we
3729 // need an available scale field.
3730 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3733 ExtAddrMode TestAddrMode = AddrMode;
3735 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3736 // [A+B + A*7] -> [B+A*8].
3737 TestAddrMode.Scale += Scale;
3738 TestAddrMode.ScaledReg = ScaleReg;
3740 // If the new address isn't legal, bail out.
3741 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3744 // It was legal, so commit it.
3745 AddrMode = TestAddrMode;
3747 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3748 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3749 // X*Scale + C*Scale to addr mode.
3750 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3751 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3752 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3753 TestAddrMode.ScaledReg = AddLHS;
3754 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
3756 // If this addressing mode is legal, commit it and remember that we folded
3757 // this instruction.
3758 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3759 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3760 AddrMode = TestAddrMode;
3765 // Otherwise, not (x+c)*scale, just return what we have.
3769 /// This is a little filter, which returns true if an addressing computation
3770 /// involving I might be folded into a load/store accessing it.
3771 /// This doesn't need to be perfect, but needs to accept at least
3772 /// the set of instructions that MatchOperationAddr can.
3773 static bool MightBeFoldableInst(Instruction *I) {
3774 switch (I->getOpcode()) {
3775 case Instruction::BitCast:
3776 case Instruction::AddrSpaceCast:
3777 // Don't touch identity bitcasts.
3778 if (I->getType() == I->getOperand(0)->getType())
3780 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3781 case Instruction::PtrToInt:
3782 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3784 case Instruction::IntToPtr:
3785 // We know the input is intptr_t, so this is foldable.
3787 case Instruction::Add:
3789 case Instruction::Mul:
3790 case Instruction::Shl:
3791 // Can only handle X*C and X << C.
3792 return isa<ConstantInt>(I->getOperand(1));
3793 case Instruction::GetElementPtr:
3800 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3801 /// \note \p Val is assumed to be the product of some type promotion.
3802 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3803 /// to be legal, as the non-promoted value would have had the same state.
3804 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3805 const DataLayout &DL, Value *Val) {
3806 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3809 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3810 // If the ISDOpcode is undefined, it was undefined before the promotion.
3813 // Otherwise, check if the promoted instruction is legal or not.
3814 return TLI.isOperationLegalOrCustom(
3815 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
3818 /// \brief Hepler class to perform type promotion.
3819 class TypePromotionHelper {
3820 /// \brief Utility function to check whether or not a sign or zero extension
3821 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3822 /// either using the operands of \p Inst or promoting \p Inst.
3823 /// The type of the extension is defined by \p IsSExt.
3824 /// In other words, check if:
3825 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
3826 /// #1 Promotion applies:
3827 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
3828 /// #2 Operand reuses:
3829 /// ext opnd1 to ConsideredExtType.
3830 /// \p PromotedInsts maps the instructions to their type before promotion.
3831 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3832 const InstrToOrigTy &PromotedInsts, bool IsSExt);
3834 /// \brief Utility function to determine if \p OpIdx should be promoted when
3835 /// promoting \p Inst.
3836 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
3837 return !(isa<SelectInst>(Inst) && OpIdx == 0);
3840 /// \brief Utility function to promote the operand of \p Ext when this
3841 /// operand is a promotable trunc or sext or zext.
3842 /// \p PromotedInsts maps the instructions to their type before promotion.
3843 /// \p CreatedInstsCost[out] contains the cost of all instructions
3844 /// created to promote the operand of Ext.
3845 /// Newly added extensions are inserted in \p Exts.
3846 /// Newly added truncates are inserted in \p Truncs.
3847 /// Should never be called directly.
3848 /// \return The promoted value which is used instead of Ext.
3849 static Value *promoteOperandForTruncAndAnyExt(
3850 Instruction *Ext, TypePromotionTransaction &TPT,
3851 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3852 SmallVectorImpl<Instruction *> *Exts,
3853 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
3855 /// \brief Utility function to promote the operand of \p Ext when this
3856 /// operand is promotable and is not a supported trunc or sext.
3857 /// \p PromotedInsts maps the instructions to their type before promotion.
3858 /// \p CreatedInstsCost[out] contains the cost of all the instructions
3859 /// created to promote the operand of Ext.
3860 /// Newly added extensions are inserted in \p Exts.
3861 /// Newly added truncates are inserted in \p Truncs.
3862 /// Should never be called directly.
3863 /// \return The promoted value which is used instead of Ext.
3864 static Value *promoteOperandForOther(Instruction *Ext,
3865 TypePromotionTransaction &TPT,
3866 InstrToOrigTy &PromotedInsts,
3867 unsigned &CreatedInstsCost,
3868 SmallVectorImpl<Instruction *> *Exts,
3869 SmallVectorImpl<Instruction *> *Truncs,
3870 const TargetLowering &TLI, bool IsSExt);
3872 /// \see promoteOperandForOther.
3873 static Value *signExtendOperandForOther(
3874 Instruction *Ext, TypePromotionTransaction &TPT,
3875 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3876 SmallVectorImpl<Instruction *> *Exts,
3877 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3878 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3879 Exts, Truncs, TLI, true);
3882 /// \see promoteOperandForOther.
3883 static Value *zeroExtendOperandForOther(
3884 Instruction *Ext, TypePromotionTransaction &TPT,
3885 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3886 SmallVectorImpl<Instruction *> *Exts,
3887 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3888 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3889 Exts, Truncs, TLI, false);
3893 /// Type for the utility function that promotes the operand of Ext.
3894 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
3895 InstrToOrigTy &PromotedInsts,
3896 unsigned &CreatedInstsCost,
3897 SmallVectorImpl<Instruction *> *Exts,
3898 SmallVectorImpl<Instruction *> *Truncs,
3899 const TargetLowering &TLI);
3900 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3901 /// action to promote the operand of \p Ext instead of using Ext.
3902 /// \return NULL if no promotable action is possible with the current
3904 /// \p InsertedInsts keeps track of all the instructions inserted by the
3905 /// other CodeGenPrepare optimizations. This information is important
3906 /// because we do not want to promote these instructions as CodeGenPrepare
3907 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3908 /// \p PromotedInsts maps the instructions to their type before promotion.
3909 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
3910 const TargetLowering &TLI,
3911 const InstrToOrigTy &PromotedInsts);
3914 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
3915 Type *ConsideredExtType,
3916 const InstrToOrigTy &PromotedInsts,
3918 // The promotion helper does not know how to deal with vector types yet.
3919 // To be able to fix that, we would need to fix the places where we
3920 // statically extend, e.g., constants and such.
3921 if (Inst->getType()->isVectorTy())
3924 // We can always get through zext.
3925 if (isa<ZExtInst>(Inst))
3928 // sext(sext) is ok too.
3929 if (IsSExt && isa<SExtInst>(Inst))
3932 // We can get through binary operator, if it is legal. In other words, the
3933 // binary operator must have a nuw or nsw flag.
3934 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3935 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3936 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3937 (IsSExt && BinOp->hasNoSignedWrap())))
3940 // Check if we can do the following simplification.
3941 // ext(trunc(opnd)) --> ext(opnd)
3942 if (!isa<TruncInst>(Inst))
3945 Value *OpndVal = Inst->getOperand(0);
3946 // Check if we can use this operand in the extension.
3947 // If the type is larger than the result type of the extension, we cannot.
3948 if (!OpndVal->getType()->isIntegerTy() ||
3949 OpndVal->getType()->getIntegerBitWidth() >
3950 ConsideredExtType->getIntegerBitWidth())
3953 // If the operand of the truncate is not an instruction, we will not have
3954 // any information on the dropped bits.
3955 // (Actually we could for constant but it is not worth the extra logic).
3956 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3960 // Check if the source of the type is narrow enough.
3961 // I.e., check that trunc just drops extended bits of the same kind of
3963 // #1 get the type of the operand and check the kind of the extended bits.
3964 const Type *OpndType;
3965 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3966 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3967 OpndType = It->second.getPointer();
3968 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3969 OpndType = Opnd->getOperand(0)->getType();
3973 // #2 check that the truncate just drops extended bits.
3974 return Inst->getType()->getIntegerBitWidth() >=
3975 OpndType->getIntegerBitWidth();
3978 TypePromotionHelper::Action TypePromotionHelper::getAction(
3979 Instruction *Ext, const SetOfInstrs &InsertedInsts,
3980 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3981 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3982 "Unexpected instruction type");
3983 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3984 Type *ExtTy = Ext->getType();
3985 bool IsSExt = isa<SExtInst>(Ext);
3986 // If the operand of the extension is not an instruction, we cannot
3988 // If it, check we can get through.
3989 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3992 // Do not promote if the operand has been added by codegenprepare.
3993 // Otherwise, it means we are undoing an optimization that is likely to be
3994 // redone, thus causing potential infinite loop.
3995 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3998 // SExt or Trunc instructions.
3999 // Return the related handler.
4000 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4001 isa<ZExtInst>(ExtOpnd))
4002 return promoteOperandForTruncAndAnyExt;
4004 // Regular instruction.
4005 // Abort early if we will have to insert non-free instructions.
4006 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4008 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4011 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4012 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
4013 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4014 SmallVectorImpl<Instruction *> *Exts,
4015 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4016 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4017 // get through it and this method should not be called.
4018 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4019 Value *ExtVal = SExt;
4020 bool HasMergedNonFreeExt = false;
4021 if (isa<ZExtInst>(SExtOpnd)) {
4022 // Replace s|zext(zext(opnd))
4024 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4026 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4027 TPT.replaceAllUsesWith(SExt, ZExt);
4028 TPT.eraseInstruction(SExt);
4031 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4033 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4035 CreatedInstsCost = 0;
4037 // Remove dead code.
4038 if (SExtOpnd->use_empty())
4039 TPT.eraseInstruction(SExtOpnd);
4041 // Check if the extension is still needed.
4042 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4043 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4046 Exts->push_back(ExtInst);
4047 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4052 // At this point we have: ext ty opnd to ty.
4053 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4054 Value *NextVal = ExtInst->getOperand(0);
4055 TPT.eraseInstruction(ExtInst, NextVal);
4059 Value *TypePromotionHelper::promoteOperandForOther(
4060 Instruction *Ext, TypePromotionTransaction &TPT,
4061 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4062 SmallVectorImpl<Instruction *> *Exts,
4063 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4065 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4066 // get through it and this method should not be called.
4067 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4068 CreatedInstsCost = 0;
4069 if (!ExtOpnd->hasOneUse()) {
4070 // ExtOpnd will be promoted.
4071 // All its uses, but Ext, will need to use a truncated value of the
4072 // promoted version.
4073 // Create the truncate now.
4074 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4075 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4076 ITrunc->removeFromParent();
4077 // Insert it just after the definition.
4078 ITrunc->insertAfter(ExtOpnd);
4080 Truncs->push_back(ITrunc);
4083 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4084 // Restore the operand of Ext (which has been replaced by the previous call
4085 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4086 TPT.setOperand(Ext, 0, ExtOpnd);
4089 // Get through the Instruction:
4090 // 1. Update its type.
4091 // 2. Replace the uses of Ext by Inst.
4092 // 3. Extend each operand that needs to be extended.
4094 // Remember the original type of the instruction before promotion.
4095 // This is useful to know that the high bits are sign extended bits.
4096 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
4097 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
4099 TPT.mutateType(ExtOpnd, Ext->getType());
4101 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4103 Instruction *ExtForOpnd = Ext;
4105 DEBUG(dbgs() << "Propagate Ext to operands\n");
4106 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4108 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4109 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4110 !shouldExtOperand(ExtOpnd, OpIdx)) {
4111 DEBUG(dbgs() << "No need to propagate\n");
4114 // Check if we can statically extend the operand.
4115 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4116 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4117 DEBUG(dbgs() << "Statically extend\n");
4118 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4119 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4120 : Cst->getValue().zext(BitWidth);
4121 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4124 // UndefValue are typed, so we have to statically sign extend them.
4125 if (isa<UndefValue>(Opnd)) {
4126 DEBUG(dbgs() << "Statically extend\n");
4127 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4131 // Otherwise we have to explicity sign extend the operand.
4132 // Check if Ext was reused to extend an operand.
4134 // If yes, create a new one.
4135 DEBUG(dbgs() << "More operands to ext\n");
4136 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4137 : TPT.createZExt(Ext, Opnd, Ext->getType());
4138 if (!isa<Instruction>(ValForExtOpnd)) {
4139 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4142 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4145 Exts->push_back(ExtForOpnd);
4146 TPT.setOperand(ExtForOpnd, 0, Opnd);
4148 // Move the sign extension before the insertion point.
4149 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4150 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4151 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
4152 // If more sext are required, new instructions will have to be created.
4153 ExtForOpnd = nullptr;
4155 if (ExtForOpnd == Ext) {
4156 DEBUG(dbgs() << "Extension is useless now\n");
4157 TPT.eraseInstruction(Ext);
4162 /// Check whether or not promoting an instruction to a wider type is profitable.
4163 /// \p NewCost gives the cost of extension instructions created by the
4165 /// \p OldCost gives the cost of extension instructions before the promotion
4166 /// plus the number of instructions that have been
4167 /// matched in the addressing mode the promotion.
4168 /// \p PromotedOperand is the value that has been promoted.
4169 /// \return True if the promotion is profitable, false otherwise.
4170 bool AddressingModeMatcher::isPromotionProfitable(
4171 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4172 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
4173 // The cost of the new extensions is greater than the cost of the
4174 // old extension plus what we folded.
4175 // This is not profitable.
4176 if (NewCost > OldCost)
4178 if (NewCost < OldCost)
4180 // The promotion is neutral but it may help folding the sign extension in
4181 // loads for instance.
4182 // Check that we did not create an illegal instruction.
4183 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4186 /// Given an instruction or constant expr, see if we can fold the operation
4187 /// into the addressing mode. If so, update the addressing mode and return
4188 /// true, otherwise return false without modifying AddrMode.
4189 /// If \p MovedAway is not NULL, it contains the information of whether or
4190 /// not AddrInst has to be folded into the addressing mode on success.
4191 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4192 /// because it has been moved away.
4193 /// Thus AddrInst must not be added in the matched instructions.
4194 /// This state can happen when AddrInst is a sext, since it may be moved away.
4195 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
4196 /// not be referenced anymore.
4197 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4200 // Avoid exponential behavior on extremely deep expression trees.
4201 if (Depth >= 5) return false;
4203 // By default, all matched instructions stay in place.
4208 case Instruction::PtrToInt:
4209 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4210 return matchAddr(AddrInst->getOperand(0), Depth);
4211 case Instruction::IntToPtr: {
4212 auto AS = AddrInst->getType()->getPointerAddressSpace();
4213 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4214 // This inttoptr is a no-op if the integer type is pointer sized.
4215 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4216 return matchAddr(AddrInst->getOperand(0), Depth);
4219 case Instruction::BitCast:
4220 // BitCast is always a noop, and we can handle it as long as it is
4221 // int->int or pointer->pointer (we don't want int<->fp or something).
4222 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
4223 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
4224 // Don't touch identity bitcasts. These were probably put here by LSR,
4225 // and we don't want to mess around with them. Assume it knows what it
4227 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4228 return matchAddr(AddrInst->getOperand(0), Depth);
4230 case Instruction::AddrSpaceCast: {
4232 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4233 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4234 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
4235 return matchAddr(AddrInst->getOperand(0), Depth);
4238 case Instruction::Add: {
4239 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4240 ExtAddrMode BackupAddrMode = AddrMode;
4241 unsigned OldSize = AddrModeInsts.size();
4242 // Start a transaction at this point.
4243 // The LHS may match but not the RHS.
4244 // Therefore, we need a higher level restoration point to undo partially
4245 // matched operation.
4246 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4247 TPT.getRestorationPoint();
4249 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
4250 matchAddr(AddrInst->getOperand(0), Depth+1))
4253 // Restore the old addr mode info.
4254 AddrMode = BackupAddrMode;
4255 AddrModeInsts.resize(OldSize);
4256 TPT.rollback(LastKnownGood);
4258 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
4259 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4260 matchAddr(AddrInst->getOperand(1), Depth+1))
4263 // Otherwise we definitely can't merge the ADD in.
4264 AddrMode = BackupAddrMode;
4265 AddrModeInsts.resize(OldSize);
4266 TPT.rollback(LastKnownGood);
4269 //case Instruction::Or:
4270 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4272 case Instruction::Mul:
4273 case Instruction::Shl: {
4274 // Can only handle X*C and X << C.
4275 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4278 int64_t Scale = RHS->getSExtValue();
4279 if (Opcode == Instruction::Shl)
4280 Scale = 1LL << Scale;
4282 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4284 case Instruction::GetElementPtr: {
4285 // Scan the GEP. We check it if it contains constant offsets and at most
4286 // one variable offset.
4287 int VariableOperand = -1;
4288 unsigned VariableScale = 0;
4290 int64_t ConstantOffset = 0;
4291 gep_type_iterator GTI = gep_type_begin(AddrInst);
4292 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4293 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
4294 const StructLayout *SL = DL.getStructLayout(STy);
4296 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4297 ConstantOffset += SL->getElementOffset(Idx);
4299 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
4300 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4301 ConstantOffset += CI->getSExtValue()*TypeSize;
4302 } else if (TypeSize) { // Scales of zero don't do anything.
4303 // We only allow one variable index at the moment.
4304 if (VariableOperand != -1)
4307 // Remember the variable index.
4308 VariableOperand = i;
4309 VariableScale = TypeSize;
4314 // A common case is for the GEP to only do a constant offset. In this case,
4315 // just add it to the disp field and check validity.
4316 if (VariableOperand == -1) {
4317 AddrMode.BaseOffs += ConstantOffset;
4318 if (ConstantOffset == 0 ||
4319 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4320 // Check to see if we can fold the base pointer in too.
4321 if (matchAddr(AddrInst->getOperand(0), Depth+1))
4324 AddrMode.BaseOffs -= ConstantOffset;
4328 // Save the valid addressing mode in case we can't match.
4329 ExtAddrMode BackupAddrMode = AddrMode;
4330 unsigned OldSize = AddrModeInsts.size();
4332 // See if the scale and offset amount is valid for this target.
4333 AddrMode.BaseOffs += ConstantOffset;
4335 // Match the base operand of the GEP.
4336 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
4337 // If it couldn't be matched, just stuff the value in a register.
4338 if (AddrMode.HasBaseReg) {
4339 AddrMode = BackupAddrMode;
4340 AddrModeInsts.resize(OldSize);
4343 AddrMode.HasBaseReg = true;
4344 AddrMode.BaseReg = AddrInst->getOperand(0);
4347 // Match the remaining variable portion of the GEP.
4348 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4350 // If it couldn't be matched, try stuffing the base into a register
4351 // instead of matching it, and retrying the match of the scale.
4352 AddrMode = BackupAddrMode;
4353 AddrModeInsts.resize(OldSize);
4354 if (AddrMode.HasBaseReg)
4356 AddrMode.HasBaseReg = true;
4357 AddrMode.BaseReg = AddrInst->getOperand(0);
4358 AddrMode.BaseOffs += ConstantOffset;
4359 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4360 VariableScale, Depth)) {
4361 // If even that didn't work, bail.
4362 AddrMode = BackupAddrMode;
4363 AddrModeInsts.resize(OldSize);
4370 case Instruction::SExt:
4371 case Instruction::ZExt: {
4372 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4376 // Try to move this ext out of the way of the addressing mode.
4377 // Ask for a method for doing so.
4378 TypePromotionHelper::Action TPH =
4379 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4383 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4384 TPT.getRestorationPoint();
4385 unsigned CreatedInstsCost = 0;
4386 unsigned ExtCost = !TLI.isExtFree(Ext);
4387 Value *PromotedOperand =
4388 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4389 // SExt has been moved away.
4390 // Thus either it will be rematched later in the recursive calls or it is
4391 // gone. Anyway, we must not fold it into the addressing mode at this point.
4395 // addr = gep base, idx
4397 // promotedOpnd = ext opnd <- no match here
4398 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4399 // addr = gep base, op <- match
4403 assert(PromotedOperand &&
4404 "TypePromotionHelper should have filtered out those cases");
4406 ExtAddrMode BackupAddrMode = AddrMode;
4407 unsigned OldSize = AddrModeInsts.size();
4409 if (!matchAddr(PromotedOperand, Depth) ||
4410 // The total of the new cost is equal to the cost of the created
4412 // The total of the old cost is equal to the cost of the extension plus
4413 // what we have saved in the addressing mode.
4414 !isPromotionProfitable(CreatedInstsCost,
4415 ExtCost + (AddrModeInsts.size() - OldSize),
4417 AddrMode = BackupAddrMode;
4418 AddrModeInsts.resize(OldSize);
4419 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
4420 TPT.rollback(LastKnownGood);
4429 /// If we can, try to add the value of 'Addr' into the current addressing mode.
4430 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4431 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
4434 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4435 // Start a transaction at this point that we will rollback if the matching
4437 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4438 TPT.getRestorationPoint();
4439 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4440 // Fold in immediates if legal for the target.
4441 AddrMode.BaseOffs += CI->getSExtValue();
4442 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4444 AddrMode.BaseOffs -= CI->getSExtValue();
4445 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4446 // If this is a global variable, try to fold it into the addressing mode.
4447 if (!AddrMode.BaseGV) {
4448 AddrMode.BaseGV = GV;
4449 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4451 AddrMode.BaseGV = nullptr;
4453 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4454 ExtAddrMode BackupAddrMode = AddrMode;
4455 unsigned OldSize = AddrModeInsts.size();
4457 // Check to see if it is possible to fold this operation.
4458 bool MovedAway = false;
4459 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4460 // This instruction may have been moved away. If so, there is nothing
4464 // Okay, it's possible to fold this. Check to see if it is actually
4465 // *profitable* to do so. We use a simple cost model to avoid increasing
4466 // register pressure too much.
4467 if (I->hasOneUse() ||
4468 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4469 AddrModeInsts.push_back(I);
4473 // It isn't profitable to do this, roll back.
4474 //cerr << "NOT FOLDING: " << *I;
4475 AddrMode = BackupAddrMode;
4476 AddrModeInsts.resize(OldSize);
4477 TPT.rollback(LastKnownGood);
4479 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4480 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4482 TPT.rollback(LastKnownGood);
4483 } else if (isa<ConstantPointerNull>(Addr)) {
4484 // Null pointer gets folded without affecting the addressing mode.
4488 // Worse case, the target should support [reg] addressing modes. :)
4489 if (!AddrMode.HasBaseReg) {
4490 AddrMode.HasBaseReg = true;
4491 AddrMode.BaseReg = Addr;
4492 // Still check for legality in case the target supports [imm] but not [i+r].
4493 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4495 AddrMode.HasBaseReg = false;
4496 AddrMode.BaseReg = nullptr;
4499 // If the base register is already taken, see if we can do [r+r].
4500 if (AddrMode.Scale == 0) {
4502 AddrMode.ScaledReg = Addr;
4503 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4506 AddrMode.ScaledReg = nullptr;
4509 TPT.rollback(LastKnownGood);
4513 /// Check to see if all uses of OpVal by the specified inline asm call are due
4514 /// to memory operands. If so, return true, otherwise return false.
4515 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
4516 const TargetMachine &TM) {
4517 const Function *F = CI->getParent()->getParent();
4518 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
4519 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
4520 TargetLowering::AsmOperandInfoVector TargetConstraints =
4521 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
4522 ImmutableCallSite(CI));
4523 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4524 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4526 // Compute the constraint code and ConstraintType to use.
4527 TLI->ComputeConstraintToUse(OpInfo, SDValue());
4529 // If this asm operand is our Value*, and if it isn't an indirect memory
4530 // operand, we can't fold it!
4531 if (OpInfo.CallOperandVal == OpVal &&
4532 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4533 !OpInfo.isIndirect))
4540 /// Recursively walk all the uses of I until we find a memory use.
4541 /// If we find an obviously non-foldable instruction, return true.
4542 /// Add the ultimately found memory instructions to MemoryUses.
4543 static bool FindAllMemoryUses(
4545 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
4546 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
4547 // If we already considered this instruction, we're done.
4548 if (!ConsideredInsts.insert(I).second)
4551 // If this is an obviously unfoldable instruction, bail out.
4552 if (!MightBeFoldableInst(I))
4555 // Loop over all the uses, recursively processing them.
4556 for (Use &U : I->uses()) {
4557 Instruction *UserI = cast<Instruction>(U.getUser());
4559 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4560 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4564 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4565 unsigned opNo = U.getOperandNo();
4566 if (opNo == 0) return true; // Storing addr, not into addr.
4567 MemoryUses.push_back(std::make_pair(SI, opNo));
4571 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
4572 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4573 if (!IA) return true;
4575 // If this is a memory operand, we're cool, otherwise bail out.
4576 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
4581 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
4588 /// Return true if Val is already known to be live at the use site that we're
4589 /// folding it into. If so, there is no cost to include it in the addressing
4590 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4591 /// instruction already.
4592 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4593 Value *KnownLive2) {
4594 // If Val is either of the known-live values, we know it is live!
4595 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4598 // All values other than instructions and arguments (e.g. constants) are live.
4599 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4601 // If Val is a constant sized alloca in the entry block, it is live, this is
4602 // true because it is just a reference to the stack/frame pointer, which is
4603 // live for the whole function.
4604 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4605 if (AI->isStaticAlloca())
4608 // Check to see if this value is already used in the memory instruction's
4609 // block. If so, it's already live into the block at the very least, so we
4610 // can reasonably fold it.
4611 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4614 /// It is possible for the addressing mode of the machine to fold the specified
4615 /// instruction into a load or store that ultimately uses it.
4616 /// However, the specified instruction has multiple uses.
4617 /// Given this, it may actually increase register pressure to fold it
4618 /// into the load. For example, consider this code:
4622 /// use(Y) -> nonload/store
4626 /// In this case, Y has multiple uses, and can be folded into the load of Z
4627 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4628 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4629 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4630 /// number of computations either.
4632 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4633 /// X was live across 'load Z' for other reasons, we actually *would* want to
4634 /// fold the addressing mode in the Z case. This would make Y die earlier.
4635 bool AddressingModeMatcher::
4636 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4637 ExtAddrMode &AMAfter) {
4638 if (IgnoreProfitability) return true;
4640 // AMBefore is the addressing mode before this instruction was folded into it,
4641 // and AMAfter is the addressing mode after the instruction was folded. Get
4642 // the set of registers referenced by AMAfter and subtract out those
4643 // referenced by AMBefore: this is the set of values which folding in this
4644 // address extends the lifetime of.
4646 // Note that there are only two potential values being referenced here,
4647 // BaseReg and ScaleReg (global addresses are always available, as are any
4648 // folded immediates).
4649 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4651 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4652 // lifetime wasn't extended by adding this instruction.
4653 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4655 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4656 ScaledReg = nullptr;
4658 // If folding this instruction (and it's subexprs) didn't extend any live
4659 // ranges, we're ok with it.
4660 if (!BaseReg && !ScaledReg)
4663 // If all uses of this instruction are ultimately load/store/inlineasm's,
4664 // check to see if their addressing modes will include this instruction. If
4665 // so, we can fold it into all uses, so it doesn't matter if it has multiple
4667 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4668 SmallPtrSet<Instruction*, 16> ConsideredInsts;
4669 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
4670 return false; // Has a non-memory, non-foldable use!
4672 // Now that we know that all uses of this instruction are part of a chain of
4673 // computation involving only operations that could theoretically be folded
4674 // into a memory use, loop over each of these uses and see if they could
4675 // *actually* fold the instruction.
4676 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4677 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4678 Instruction *User = MemoryUses[i].first;
4679 unsigned OpNo = MemoryUses[i].second;
4681 // Get the access type of this use. If the use isn't a pointer, we don't
4682 // know what it accesses.
4683 Value *Address = User->getOperand(OpNo);
4684 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4687 Type *AddressAccessTy = AddrTy->getElementType();
4688 unsigned AS = AddrTy->getAddressSpace();
4690 // Do a match against the root of this address, ignoring profitability. This
4691 // will tell us if the addressing mode for the memory operation will
4692 // *actually* cover the shared instruction.
4694 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4695 TPT.getRestorationPoint();
4696 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
4697 MemoryInst, Result, InsertedInsts,
4698 PromotedInsts, TPT);
4699 Matcher.IgnoreProfitability = true;
4700 bool Success = Matcher.matchAddr(Address, 0);
4701 (void)Success; assert(Success && "Couldn't select *anything*?");
4703 // The match was to check the profitability, the changes made are not
4704 // part of the original matcher. Therefore, they should be dropped
4705 // otherwise the original matcher will not present the right state.
4706 TPT.rollback(LastKnownGood);
4708 // If the match didn't cover I, then it won't be shared by it.
4709 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
4710 I) == MatchedAddrModeInsts.end())
4713 MatchedAddrModeInsts.clear();
4719 } // end anonymous namespace
4721 /// Return true if the specified values are defined in a
4722 /// different basic block than BB.
4723 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4724 if (Instruction *I = dyn_cast<Instruction>(V))
4725 return I->getParent() != BB;
4729 /// Load and Store Instructions often have addressing modes that can do
4730 /// significant amounts of computation. As such, instruction selection will try
4731 /// to get the load or store to do as much computation as possible for the
4732 /// program. The problem is that isel can only see within a single block. As
4733 /// such, we sink as much legal addressing mode work into the block as possible.
4735 /// This method is used to optimize both load/store and inline asms with memory
4737 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
4738 Type *AccessTy, unsigned AddrSpace) {
4741 // Try to collapse single-value PHI nodes. This is necessary to undo
4742 // unprofitable PRE transformations.
4743 SmallVector<Value*, 8> worklist;
4744 SmallPtrSet<Value*, 16> Visited;
4745 worklist.push_back(Addr);
4747 // Use a worklist to iteratively look through PHI nodes, and ensure that
4748 // the addressing mode obtained from the non-PHI roots of the graph
4750 Value *Consensus = nullptr;
4751 unsigned NumUsesConsensus = 0;
4752 bool IsNumUsesConsensusValid = false;
4753 SmallVector<Instruction*, 16> AddrModeInsts;
4754 ExtAddrMode AddrMode;
4755 TypePromotionTransaction TPT;
4756 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4757 TPT.getRestorationPoint();
4758 while (!worklist.empty()) {
4759 Value *V = worklist.back();
4760 worklist.pop_back();
4762 // Break use-def graph loops.
4763 if (!Visited.insert(V).second) {
4764 Consensus = nullptr;
4768 // For a PHI node, push all of its incoming values.
4769 if (PHINode *P = dyn_cast<PHINode>(V)) {
4770 for (Value *IncValue : P->incoming_values())
4771 worklist.push_back(IncValue);
4775 // For non-PHIs, determine the addressing mode being computed.
4776 SmallVector<Instruction*, 16> NewAddrModeInsts;
4777 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4778 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
4779 InsertedInsts, PromotedInsts, TPT);
4781 // This check is broken into two cases with very similar code to avoid using
4782 // getNumUses() as much as possible. Some values have a lot of uses, so
4783 // calling getNumUses() unconditionally caused a significant compile-time
4787 AddrMode = NewAddrMode;
4788 AddrModeInsts = NewAddrModeInsts;
4790 } else if (NewAddrMode == AddrMode) {
4791 if (!IsNumUsesConsensusValid) {
4792 NumUsesConsensus = Consensus->getNumUses();
4793 IsNumUsesConsensusValid = true;
4796 // Ensure that the obtained addressing mode is equivalent to that obtained
4797 // for all other roots of the PHI traversal. Also, when choosing one
4798 // such root as representative, select the one with the most uses in order
4799 // to keep the cost modeling heuristics in AddressingModeMatcher
4801 unsigned NumUses = V->getNumUses();
4802 if (NumUses > NumUsesConsensus) {
4804 NumUsesConsensus = NumUses;
4805 AddrModeInsts = NewAddrModeInsts;
4810 Consensus = nullptr;
4814 // If the addressing mode couldn't be determined, or if multiple different
4815 // ones were determined, bail out now.
4817 TPT.rollback(LastKnownGood);
4822 // Check to see if any of the instructions supersumed by this addr mode are
4823 // non-local to I's BB.
4824 bool AnyNonLocal = false;
4825 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
4826 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
4832 // If all the instructions matched are already in this BB, don't do anything.
4834 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
4838 // Insert this computation right after this user. Since our caller is
4839 // scanning from the top of the BB to the bottom, reuse of the expr are
4840 // guaranteed to happen later.
4841 IRBuilder<> Builder(MemoryInst);
4843 // Now that we determined the addressing expression we want to use and know
4844 // that we have to sink it into this block. Check to see if we have already
4845 // done this for some other load/store instr in this block. If so, reuse the
4847 Value *&SunkAddr = SunkAddrs[Addr];
4849 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
4850 << *MemoryInst << "\n");
4851 if (SunkAddr->getType() != Addr->getType())
4852 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4853 } else if (AddrSinkUsingGEPs ||
4854 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
4855 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
4857 // By default, we use the GEP-based method when AA is used later. This
4858 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4859 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4860 << *MemoryInst << "\n");
4861 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4862 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
4864 // First, find the pointer.
4865 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4866 ResultPtr = AddrMode.BaseReg;
4867 AddrMode.BaseReg = nullptr;
4870 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4871 // We can't add more than one pointer together, nor can we scale a
4872 // pointer (both of which seem meaningless).
4873 if (ResultPtr || AddrMode.Scale != 1)
4876 ResultPtr = AddrMode.ScaledReg;
4880 if (AddrMode.BaseGV) {
4884 ResultPtr = AddrMode.BaseGV;
4887 // If the real base value actually came from an inttoptr, then the matcher
4888 // will look through it and provide only the integer value. In that case,
4890 if (!ResultPtr && AddrMode.BaseReg) {
4892 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
4893 AddrMode.BaseReg = nullptr;
4894 } else if (!ResultPtr && AddrMode.Scale == 1) {
4896 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4901 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4902 SunkAddr = Constant::getNullValue(Addr->getType());
4903 } else if (!ResultPtr) {
4907 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4908 Type *I8Ty = Builder.getInt8Ty();
4910 // Start with the base register. Do this first so that subsequent address
4911 // matching finds it last, which will prevent it from trying to match it
4912 // as the scaled value in case it happens to be a mul. That would be
4913 // problematic if we've sunk a different mul for the scale, because then
4914 // we'd end up sinking both muls.
4915 if (AddrMode.BaseReg) {
4916 Value *V = AddrMode.BaseReg;
4917 if (V->getType() != IntPtrTy)
4918 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4923 // Add the scale value.
4924 if (AddrMode.Scale) {
4925 Value *V = AddrMode.ScaledReg;
4926 if (V->getType() == IntPtrTy) {
4928 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4929 cast<IntegerType>(V->getType())->getBitWidth()) {
4930 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4932 // It is only safe to sign extend the BaseReg if we know that the math
4933 // required to create it did not overflow before we extend it. Since
4934 // the original IR value was tossed in favor of a constant back when
4935 // the AddrMode was created we need to bail out gracefully if widths
4936 // do not match instead of extending it.
4937 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4938 if (I && (ResultIndex != AddrMode.BaseReg))
4939 I->eraseFromParent();
4943 if (AddrMode.Scale != 1)
4944 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4947 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4952 // Add in the Base Offset if present.
4953 if (AddrMode.BaseOffs) {
4954 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4956 // We need to add this separately from the scale above to help with
4957 // SDAG consecutive load/store merging.
4958 if (ResultPtr->getType() != I8PtrTy)
4959 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4960 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4967 SunkAddr = ResultPtr;
4969 if (ResultPtr->getType() != I8PtrTy)
4970 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4971 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4974 if (SunkAddr->getType() != Addr->getType())
4975 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4978 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4979 << *MemoryInst << "\n");
4980 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4981 Value *Result = nullptr;
4983 // Start with the base register. Do this first so that subsequent address
4984 // matching finds it last, which will prevent it from trying to match it
4985 // as the scaled value in case it happens to be a mul. That would be
4986 // problematic if we've sunk a different mul for the scale, because then
4987 // we'd end up sinking both muls.
4988 if (AddrMode.BaseReg) {
4989 Value *V = AddrMode.BaseReg;
4990 if (V->getType()->isPointerTy())
4991 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4992 if (V->getType() != IntPtrTy)
4993 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4997 // Add the scale value.
4998 if (AddrMode.Scale) {
4999 Value *V = AddrMode.ScaledReg;
5000 if (V->getType() == IntPtrTy) {
5002 } else if (V->getType()->isPointerTy()) {
5003 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
5004 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
5005 cast<IntegerType>(V->getType())->getBitWidth()) {
5006 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
5008 // It is only safe to sign extend the BaseReg if we know that the math
5009 // required to create it did not overflow before we extend it. Since
5010 // the original IR value was tossed in favor of a constant back when
5011 // the AddrMode was created we need to bail out gracefully if widths
5012 // do not match instead of extending it.
5013 Instruction *I = dyn_cast_or_null<Instruction>(Result);
5014 if (I && (Result != AddrMode.BaseReg))
5015 I->eraseFromParent();
5018 if (AddrMode.Scale != 1)
5019 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
5022 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5027 // Add in the BaseGV if present.
5028 if (AddrMode.BaseGV) {
5029 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
5031 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5036 // Add in the Base Offset if present.
5037 if (AddrMode.BaseOffs) {
5038 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
5040 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5046 SunkAddr = Constant::getNullValue(Addr->getType());
5048 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
5051 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
5053 // If we have no uses, recursively delete the value and all dead instructions
5055 if (Repl->use_empty()) {
5056 // This can cause recursive deletion, which can invalidate our iterator.
5057 // Use a WeakVH to hold onto it in case this happens.
5058 WeakVH IterHandle(&*CurInstIterator);
5059 BasicBlock *BB = CurInstIterator->getParent();
5061 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
5063 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
5064 // If the iterator instruction was recursively deleted, start over at the
5065 // start of the block.
5066 CurInstIterator = BB->begin();
5074 /// If there are any memory operands, use OptimizeMemoryInst to sink their
5075 /// address computing into the block when possible / profitable.
5076 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
5077 bool MadeChange = false;
5079 const TargetRegisterInfo *TRI =
5080 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
5081 TargetLowering::AsmOperandInfoVector TargetConstraints =
5082 TLI->ParseConstraints(*DL, TRI, CS);
5084 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5085 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
5087 // Compute the constraint code and ConstraintType to use.
5088 TLI->ComputeConstraintToUse(OpInfo, SDValue());
5090 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5091 OpInfo.isIndirect) {
5092 Value *OpVal = CS->getArgOperand(ArgNo++);
5093 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
5094 } else if (OpInfo.Type == InlineAsm::isInput)
5101 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
5102 /// sign extensions.
5103 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
5104 assert(!Inst->use_empty() && "Input must have at least one use");
5105 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
5106 bool IsSExt = isa<SExtInst>(FirstUser);
5107 Type *ExtTy = FirstUser->getType();
5108 for (const User *U : Inst->users()) {
5109 const Instruction *UI = cast<Instruction>(U);
5110 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
5112 Type *CurTy = UI->getType();
5113 // Same input and output types: Same instruction after CSE.
5117 // If IsSExt is true, we are in this situation:
5119 // b = sext ty1 a to ty2
5120 // c = sext ty1 a to ty3
5121 // Assuming ty2 is shorter than ty3, this could be turned into:
5123 // b = sext ty1 a to ty2
5124 // c = sext ty2 b to ty3
5125 // However, the last sext is not free.
5129 // This is a ZExt, maybe this is free to extend from one type to another.
5130 // In that case, we would not account for a different use.
5133 if (ExtTy->getScalarType()->getIntegerBitWidth() >
5134 CurTy->getScalarType()->getIntegerBitWidth()) {
5142 if (!TLI.isZExtFree(NarrowTy, LargeTy))
5145 // All uses are the same or can be derived from one another for free.
5149 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
5150 /// load instruction.
5151 /// If an ext(load) can be formed, it is returned via \p LI for the load
5152 /// and \p Inst for the extension.
5153 /// Otherwise LI == nullptr and Inst == nullptr.
5154 /// When some promotion happened, \p TPT contains the proper state to
5157 /// \return true when promoting was necessary to expose the ext(load)
5158 /// opportunity, false otherwise.
5162 /// %ld = load i32* %addr
5163 /// %add = add nuw i32 %ld, 4
5164 /// %zext = zext i32 %add to i64
5168 /// %ld = load i32* %addr
5169 /// %zext = zext i32 %ld to i64
5170 /// %add = add nuw i64 %zext, 4
5172 /// Thanks to the promotion, we can match zext(load i32*) to i64.
5173 bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
5174 LoadInst *&LI, Instruction *&Inst,
5175 const SmallVectorImpl<Instruction *> &Exts,
5176 unsigned CreatedInstsCost = 0) {
5177 // Iterate over all the extensions to see if one form an ext(load).
5178 for (auto I : Exts) {
5179 // Check if we directly have ext(load).
5180 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
5182 // No promotion happened here.
5185 // Check whether or not we want to do any promotion.
5186 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
5188 // Get the action to perform the promotion.
5189 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
5190 I, InsertedInsts, *TLI, PromotedInsts);
5191 // Check if we can promote.
5194 // Save the current state.
5195 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5196 TPT.getRestorationPoint();
5197 SmallVector<Instruction *, 4> NewExts;
5198 unsigned NewCreatedInstsCost = 0;
5199 unsigned ExtCost = !TLI->isExtFree(I);
5201 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5202 &NewExts, nullptr, *TLI);
5203 assert(PromotedVal &&
5204 "TypePromotionHelper should have filtered out those cases");
5206 // We would be able to merge only one extension in a load.
5207 // Therefore, if we have more than 1 new extension we heuristically
5208 // cut this search path, because it means we degrade the code quality.
5209 // With exactly 2, the transformation is neutral, because we will merge
5210 // one extension but leave one. However, we optimistically keep going,
5211 // because the new extension may be removed too.
5212 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
5213 TotalCreatedInstsCost -= ExtCost;
5214 if (!StressExtLdPromotion &&
5215 (TotalCreatedInstsCost > 1 ||
5216 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
5217 // The promotion is not profitable, rollback to the previous state.
5218 TPT.rollback(LastKnownGood);
5221 // The promotion is profitable.
5222 // Check if it exposes an ext(load).
5223 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
5224 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5225 // If we have created a new extension, i.e., now we have two
5226 // extensions. We must make sure one of them is merged with
5227 // the load, otherwise we may degrade the code quality.
5228 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
5229 // Promotion happened.
5231 // If this does not help to expose an ext(load) then, rollback.
5232 TPT.rollback(LastKnownGood);
5234 // None of the extension can form an ext(load).
5240 /// Move a zext or sext fed by a load into the same basic block as the load,
5241 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
5242 /// extend into the load.
5243 /// \p I[in/out] the extension may be modified during the process if some
5244 /// promotions apply.
5246 bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
5247 // Try to promote a chain of computation if it allows to form
5248 // an extended load.
5249 TypePromotionTransaction TPT;
5250 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5251 TPT.getRestorationPoint();
5252 SmallVector<Instruction *, 1> Exts;
5254 // Look for a load being extended.
5255 LoadInst *LI = nullptr;
5256 Instruction *OldExt = I;
5257 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
5259 assert(!HasPromoted && !LI && "If we did not match any load instruction "
5260 "the code must remain the same");
5265 // If they're already in the same block, there's nothing to do.
5266 // Make the cheap checks first if we did not promote.
5267 // If we promoted, we need to check if it is indeed profitable.
5268 if (!HasPromoted && LI->getParent() == I->getParent())
5271 EVT VT = TLI->getValueType(*DL, I->getType());
5272 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
5274 // If the load has other users and the truncate is not free, this probably
5275 // isn't worthwhile.
5276 if (!LI->hasOneUse() && TLI &&
5277 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
5278 !TLI->isTruncateFree(I->getType(), LI->getType())) {
5280 TPT.rollback(LastKnownGood);
5284 // Check whether the target supports casts folded into loads.
5286 if (isa<ZExtInst>(I))
5287 LType = ISD::ZEXTLOAD;
5289 assert(isa<SExtInst>(I) && "Unexpected ext type!");
5290 LType = ISD::SEXTLOAD;
5292 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
5294 TPT.rollback(LastKnownGood);
5298 // Move the extend into the same block as the load, so that SelectionDAG
5301 I->removeFromParent();
5307 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
5308 BasicBlock *DefBB = I->getParent();
5310 // If the result of a {s|z}ext and its source are both live out, rewrite all
5311 // other uses of the source with result of extension.
5312 Value *Src = I->getOperand(0);
5313 if (Src->hasOneUse())
5316 // Only do this xform if truncating is free.
5317 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
5320 // Only safe to perform the optimization if the source is also defined in
5322 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
5325 bool DefIsLiveOut = false;
5326 for (User *U : I->users()) {
5327 Instruction *UI = cast<Instruction>(U);
5329 // Figure out which BB this ext is used in.
5330 BasicBlock *UserBB = UI->getParent();
5331 if (UserBB == DefBB) continue;
5332 DefIsLiveOut = true;
5338 // Make sure none of the uses are PHI nodes.
5339 for (User *U : Src->users()) {
5340 Instruction *UI = cast<Instruction>(U);
5341 BasicBlock *UserBB = UI->getParent();
5342 if (UserBB == DefBB) continue;
5343 // Be conservative. We don't want this xform to end up introducing
5344 // reloads just before load / store instructions.
5345 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5349 // InsertedTruncs - Only insert one trunc in each block once.
5350 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5352 bool MadeChange = false;
5353 for (Use &U : Src->uses()) {
5354 Instruction *User = cast<Instruction>(U.getUser());
5356 // Figure out which BB this ext is used in.
5357 BasicBlock *UserBB = User->getParent();
5358 if (UserBB == DefBB) continue;
5360 // Both src and def are live in this block. Rewrite the use.
5361 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5363 if (!InsertedTrunc) {
5364 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5365 assert(InsertPt != UserBB->end());
5366 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
5367 InsertedInsts.insert(InsertedTrunc);
5370 // Replace a use of the {s|z}ext source with a use of the result.
5379 // Find loads whose uses only use some of the loaded value's bits. Add an "and"
5380 // just after the load if the target can fold this into one extload instruction,
5381 // with the hope of eliminating some of the other later "and" instructions using
5382 // the loaded value. "and"s that are made trivially redundant by the insertion
5383 // of the new "and" are removed by this function, while others (e.g. those whose
5384 // path from the load goes through a phi) are left for isel to potentially
5417 // becomes (after a call to optimizeLoadExt for each load):
5421 // x1' = and x1, 0xff
5425 // x2' = and x2, 0xff
5432 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5434 if (!Load->isSimple() ||
5435 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5438 // Skip loads we've already transformed or have no reason to transform.
5439 if (Load->hasOneUse()) {
5440 User *LoadUser = *Load->user_begin();
5441 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
5442 !dyn_cast<PHINode>(LoadUser))
5446 // Look at all uses of Load, looking through phis, to determine how many bits
5447 // of the loaded value are needed.
5448 SmallVector<Instruction *, 8> WorkList;
5449 SmallPtrSet<Instruction *, 16> Visited;
5450 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5451 for (auto *U : Load->users())
5452 WorkList.push_back(cast<Instruction>(U));
5454 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5455 unsigned BitWidth = LoadResultVT.getSizeInBits();
5456 APInt DemandBits(BitWidth, 0);
5457 APInt WidestAndBits(BitWidth, 0);
5459 while (!WorkList.empty()) {
5460 Instruction *I = WorkList.back();
5461 WorkList.pop_back();
5463 // Break use-def graph loops.
5464 if (!Visited.insert(I).second)
5467 // For a PHI node, push all of its users.
5468 if (auto *Phi = dyn_cast<PHINode>(I)) {
5469 for (auto *U : Phi->users())
5470 WorkList.push_back(cast<Instruction>(U));
5474 switch (I->getOpcode()) {
5475 case llvm::Instruction::And: {
5476 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5479 APInt AndBits = AndC->getValue();
5480 DemandBits |= AndBits;
5481 // Keep track of the widest and mask we see.
5482 if (AndBits.ugt(WidestAndBits))
5483 WidestAndBits = AndBits;
5484 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5485 AndsToMaybeRemove.push_back(I);
5489 case llvm::Instruction::Shl: {
5490 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5493 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5494 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
5495 DemandBits |= ShlDemandBits;
5499 case llvm::Instruction::Trunc: {
5500 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5501 unsigned TruncBitWidth = TruncVT.getSizeInBits();
5502 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
5503 DemandBits |= TruncBits;
5512 uint32_t ActiveBits = DemandBits.getActiveBits();
5513 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5514 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5515 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5516 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5517 // followed by an AND.
5518 // TODO: Look into removing this restriction by fixing backends to either
5519 // return false for isLoadExtLegal for i1 or have them select this pattern to
5520 // a single instruction.
5522 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5523 // mask, since these are the only ands that will be removed by isel.
5524 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
5525 WidestAndBits != DemandBits)
5528 LLVMContext &Ctx = Load->getType()->getContext();
5529 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5530 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5532 // Reject cases that won't be matched as extloads.
5533 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5534 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5537 IRBuilder<> Builder(Load->getNextNode());
5538 auto *NewAnd = dyn_cast<Instruction>(
5539 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5541 // Replace all uses of load with new and (except for the use of load in the
5543 Load->replaceAllUsesWith(NewAnd);
5544 NewAnd->setOperand(0, Load);
5546 // Remove any and instructions that are now redundant.
5547 for (auto *And : AndsToMaybeRemove)
5548 // Check that the and mask is the same as the one we decided to put on the
5550 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5551 And->replaceAllUsesWith(NewAnd);
5552 if (&*CurInstIterator == And)
5553 CurInstIterator = std::next(And->getIterator());
5554 And->eraseFromParent();
5562 /// Check if V (an operand of a select instruction) is an expensive instruction
5563 /// that is only used once.
5564 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5565 auto *I = dyn_cast<Instruction>(V);
5566 // If it's safe to speculatively execute, then it should not have side
5567 // effects; therefore, it's safe to sink and possibly *not* execute.
5568 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5569 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5572 /// Returns true if a SelectInst should be turned into an explicit branch.
5573 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
5575 // FIXME: This should use the same heuristics as IfConversion to determine
5576 // whether a select is better represented as a branch. This requires that
5577 // branch probability metadata is preserved for the select, which is not the
5580 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5582 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5583 // comparison condition. If the compare has more than one use, there's
5584 // probably another cmov or setcc around, so it's not worth emitting a branch.
5585 if (!Cmp || !Cmp->hasOneUse())
5588 Value *CmpOp0 = Cmp->getOperand(0);
5589 Value *CmpOp1 = Cmp->getOperand(1);
5591 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
5592 // on a load from memory. But if the load is used more than once, do not
5593 // change the select to a branch because the load is probably needed
5594 // regardless of whether the branch is taken or not.
5595 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
5596 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
5599 // If either operand of the select is expensive and only needed on one side
5600 // of the select, we should form a branch.
5601 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5602 sinkSelectOperand(TTI, SI->getFalseValue()))
5609 /// If we have a SelectInst that will likely profit from branch prediction,
5610 /// turn it into a branch.
5611 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5612 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5614 // Can we convert the 'select' to CF ?
5615 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
5618 TargetLowering::SelectSupportKind SelectKind;
5620 SelectKind = TargetLowering::VectorMaskSelect;
5621 else if (SI->getType()->isVectorTy())
5622 SelectKind = TargetLowering::ScalarCondVectorVal;
5624 SelectKind = TargetLowering::ScalarValSelect;
5626 // Do we have efficient codegen support for this kind of 'selects' ?
5627 if (TLI->isSelectSupported(SelectKind)) {
5628 // We have efficient codegen support for the select instruction.
5629 // Check if it is profitable to keep this 'select'.
5630 if (!TLI->isPredictableSelectExpensive() ||
5631 !isFormingBranchFromSelectProfitable(TTI, SI))
5637 // Transform a sequence like this:
5639 // %cmp = cmp uge i32 %a, %b
5640 // %sel = select i1 %cmp, i32 %c, i32 %d
5644 // %cmp = cmp uge i32 %a, %b
5645 // br i1 %cmp, label %select.true, label %select.false
5647 // br label %select.end
5649 // br label %select.end
5651 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5653 // In addition, we may sink instructions that produce %c or %d from
5654 // the entry block into the destination(s) of the new branch.
5655 // If the true or false blocks do not contain a sunken instruction, that
5656 // block and its branch may be optimized away. In that case, one side of the
5657 // first branch will point directly to select.end, and the corresponding PHI
5658 // predecessor block will be the start block.
5660 // First, we split the block containing the select into 2 blocks.
5661 BasicBlock *StartBlock = SI->getParent();
5662 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
5663 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
5665 // Delete the unconditional branch that was just created by the split.
5666 StartBlock->getTerminator()->eraseFromParent();
5668 // These are the new basic blocks for the conditional branch.
5669 // At least one will become an actual new basic block.
5670 BasicBlock *TrueBlock = nullptr;
5671 BasicBlock *FalseBlock = nullptr;
5673 // Sink expensive instructions into the conditional blocks to avoid executing
5674 // them speculatively.
5675 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5676 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5677 EndBlock->getParent(), EndBlock);
5678 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5679 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5680 TrueInst->moveBefore(TrueBranch);
5682 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5683 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5684 EndBlock->getParent(), EndBlock);
5685 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5686 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5687 FalseInst->moveBefore(FalseBranch);
5690 // If there was nothing to sink, then arbitrarily choose the 'false' side
5691 // for a new input value to the PHI.
5692 if (TrueBlock == FalseBlock) {
5693 assert(TrueBlock == nullptr &&
5694 "Unexpected basic block transform while optimizing select");
5696 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5697 EndBlock->getParent(), EndBlock);
5698 BranchInst::Create(EndBlock, FalseBlock);
5701 // Insert the real conditional branch based on the original condition.
5702 // If we did not create a new block for one of the 'true' or 'false' paths
5703 // of the condition, it means that side of the branch goes to the end block
5704 // directly and the path originates from the start block from the point of
5705 // view of the new PHI.
5706 if (TrueBlock == nullptr) {
5707 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
5708 TrueBlock = StartBlock;
5709 } else if (FalseBlock == nullptr) {
5710 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
5711 FalseBlock = StartBlock;
5713 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
5716 // The select itself is replaced with a PHI Node.
5717 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5719 PN->addIncoming(SI->getTrueValue(), TrueBlock);
5720 PN->addIncoming(SI->getFalseValue(), FalseBlock);
5722 SI->replaceAllUsesWith(PN);
5723 SI->eraseFromParent();
5725 // Instruct OptimizeBlock to skip to the next block.
5726 CurInstIterator = StartBlock->end();
5727 ++NumSelectsExpanded;
5731 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
5732 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5734 for (unsigned i = 0; i < Mask.size(); ++i) {
5735 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5737 SplatElem = Mask[i];
5743 /// Some targets have expensive vector shifts if the lanes aren't all the same
5744 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5745 /// it's often worth sinking a shufflevector splat down to its use so that
5746 /// codegen can spot all lanes are identical.
5747 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
5748 BasicBlock *DefBB = SVI->getParent();
5750 // Only do this xform if variable vector shifts are particularly expensive.
5751 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5754 // We only expect better codegen by sinking a shuffle if we can recognise a
5756 if (!isBroadcastShuffle(SVI))
5759 // InsertedShuffles - Only insert a shuffle in each block once.
5760 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5762 bool MadeChange = false;
5763 for (User *U : SVI->users()) {
5764 Instruction *UI = cast<Instruction>(U);
5766 // Figure out which BB this ext is used in.
5767 BasicBlock *UserBB = UI->getParent();
5768 if (UserBB == DefBB) continue;
5770 // For now only apply this when the splat is used by a shift instruction.
5771 if (!UI->isShift()) continue;
5773 // Everything checks out, sink the shuffle if the user's block doesn't
5774 // already have a copy.
5775 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5777 if (!InsertedShuffle) {
5778 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5779 assert(InsertPt != UserBB->end());
5781 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5782 SVI->getOperand(2), "", &*InsertPt);
5785 UI->replaceUsesOfWith(SVI, InsertedShuffle);
5789 // If we removed all uses, nuke the shuffle.
5790 if (SVI->use_empty()) {
5791 SVI->eraseFromParent();
5798 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5802 Value *Cond = SI->getCondition();
5803 Type *OldType = Cond->getType();
5804 LLVMContext &Context = Cond->getContext();
5805 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5806 unsigned RegWidth = RegType.getSizeInBits();
5808 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5811 // If the register width is greater than the type width, expand the condition
5812 // of the switch instruction and each case constant to the width of the
5813 // register. By widening the type of the switch condition, subsequent
5814 // comparisons (for case comparisons) will not need to be extended to the
5815 // preferred register width, so we will potentially eliminate N-1 extends,
5816 // where N is the number of cases in the switch.
5817 auto *NewType = Type::getIntNTy(Context, RegWidth);
5819 // Zero-extend the switch condition and case constants unless the switch
5820 // condition is a function argument that is already being sign-extended.
5821 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5822 // everything instead.
5823 Instruction::CastOps ExtType = Instruction::ZExt;
5824 if (auto *Arg = dyn_cast<Argument>(Cond))
5825 if (Arg->hasSExtAttr())
5826 ExtType = Instruction::SExt;
5828 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5829 ExtInst->insertBefore(SI);
5830 SI->setCondition(ExtInst);
5831 for (SwitchInst::CaseIt Case : SI->cases()) {
5832 APInt NarrowConst = Case.getCaseValue()->getValue();
5833 APInt WideConst = (ExtType == Instruction::ZExt) ?
5834 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5835 Case.setValue(ConstantInt::get(Context, WideConst));
5842 /// \brief Helper class to promote a scalar operation to a vector one.
5843 /// This class is used to move downward extractelement transition.
5845 /// a = vector_op <2 x i32>
5846 /// b = extractelement <2 x i32> a, i32 0
5851 /// a = vector_op <2 x i32>
5852 /// c = vector_op a (equivalent to scalar_op on the related lane)
5853 /// * d = extractelement <2 x i32> c, i32 0
5855 /// Assuming both extractelement and store can be combine, we get rid of the
5857 class VectorPromoteHelper {
5858 /// DataLayout associated with the current module.
5859 const DataLayout &DL;
5861 /// Used to perform some checks on the legality of vector operations.
5862 const TargetLowering &TLI;
5864 /// Used to estimated the cost of the promoted chain.
5865 const TargetTransformInfo &TTI;
5867 /// The transition being moved downwards.
5868 Instruction *Transition;
5869 /// The sequence of instructions to be promoted.
5870 SmallVector<Instruction *, 4> InstsToBePromoted;
5871 /// Cost of combining a store and an extract.
5872 unsigned StoreExtractCombineCost;
5873 /// Instruction that will be combined with the transition.
5874 Instruction *CombineInst;
5876 /// \brief The instruction that represents the current end of the transition.
5877 /// Since we are faking the promotion until we reach the end of the chain
5878 /// of computation, we need a way to get the current end of the transition.
5879 Instruction *getEndOfTransition() const {
5880 if (InstsToBePromoted.empty())
5882 return InstsToBePromoted.back();
5885 /// \brief Return the index of the original value in the transition.
5886 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5887 /// c, is at index 0.
5888 unsigned getTransitionOriginalValueIdx() const {
5889 assert(isa<ExtractElementInst>(Transition) &&
5890 "Other kind of transitions are not supported yet");
5894 /// \brief Return the index of the index in the transition.
5895 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5897 unsigned getTransitionIdx() const {
5898 assert(isa<ExtractElementInst>(Transition) &&
5899 "Other kind of transitions are not supported yet");
5903 /// \brief Get the type of the transition.
5904 /// This is the type of the original value.
5905 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5906 /// transition is <2 x i32>.
5907 Type *getTransitionType() const {
5908 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5911 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5912 /// I.e., we have the following sequence:
5913 /// Def = Transition <ty1> a to <ty2>
5914 /// b = ToBePromoted <ty2> Def, ...
5916 /// b = ToBePromoted <ty1> a, ...
5917 /// Def = Transition <ty1> ToBePromoted to <ty2>
5918 void promoteImpl(Instruction *ToBePromoted);
5920 /// \brief Check whether or not it is profitable to promote all the
5921 /// instructions enqueued to be promoted.
5922 bool isProfitableToPromote() {
5923 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5924 unsigned Index = isa<ConstantInt>(ValIdx)
5925 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5927 Type *PromotedType = getTransitionType();
5929 StoreInst *ST = cast<StoreInst>(CombineInst);
5930 unsigned AS = ST->getPointerAddressSpace();
5931 unsigned Align = ST->getAlignment();
5932 // Check if this store is supported.
5933 if (!TLI.allowsMisalignedMemoryAccesses(
5934 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5936 // If this is not supported, there is no way we can combine
5937 // the extract with the store.
5941 // The scalar chain of computation has to pay for the transition
5942 // scalar to vector.
5943 // The vector chain has to account for the combining cost.
5944 uint64_t ScalarCost =
5945 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5946 uint64_t VectorCost = StoreExtractCombineCost;
5947 for (const auto &Inst : InstsToBePromoted) {
5948 // Compute the cost.
5949 // By construction, all instructions being promoted are arithmetic ones.
5950 // Moreover, one argument is a constant that can be viewed as a splat
5952 Value *Arg0 = Inst->getOperand(0);
5953 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5954 isa<ConstantFP>(Arg0);
5955 TargetTransformInfo::OperandValueKind Arg0OVK =
5956 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5957 : TargetTransformInfo::OK_AnyValue;
5958 TargetTransformInfo::OperandValueKind Arg1OVK =
5959 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5960 : TargetTransformInfo::OK_AnyValue;
5961 ScalarCost += TTI.getArithmeticInstrCost(
5962 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5963 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5966 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5967 << ScalarCost << "\nVector: " << VectorCost << '\n');
5968 return ScalarCost > VectorCost;
5971 /// \brief Generate a constant vector with \p Val with the same
5972 /// number of elements as the transition.
5973 /// \p UseSplat defines whether or not \p Val should be replicated
5974 /// across the whole vector.
5975 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5976 /// otherwise we generate a vector with as many undef as possible:
5977 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5978 /// used at the index of the extract.
5979 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5980 unsigned ExtractIdx = UINT_MAX;
5982 // If we cannot determine where the constant must be, we have to
5983 // use a splat constant.
5984 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5985 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5986 ExtractIdx = CstVal->getSExtValue();
5991 unsigned End = getTransitionType()->getVectorNumElements();
5993 return ConstantVector::getSplat(End, Val);
5995 SmallVector<Constant *, 4> ConstVec;
5996 UndefValue *UndefVal = UndefValue::get(Val->getType());
5997 for (unsigned Idx = 0; Idx != End; ++Idx) {
5998 if (Idx == ExtractIdx)
5999 ConstVec.push_back(Val);
6001 ConstVec.push_back(UndefVal);
6003 return ConstantVector::get(ConstVec);
6006 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
6007 /// in \p Use can trigger undefined behavior.
6008 static bool canCauseUndefinedBehavior(const Instruction *Use,
6009 unsigned OperandIdx) {
6010 // This is not safe to introduce undef when the operand is on
6011 // the right hand side of a division-like instruction.
6012 if (OperandIdx != 1)
6014 switch (Use->getOpcode()) {
6017 case Instruction::SDiv:
6018 case Instruction::UDiv:
6019 case Instruction::SRem:
6020 case Instruction::URem:
6022 case Instruction::FDiv:
6023 case Instruction::FRem:
6024 return !Use->hasNoNaNs();
6026 llvm_unreachable(nullptr);
6030 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6031 const TargetTransformInfo &TTI, Instruction *Transition,
6032 unsigned CombineCost)
6033 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
6034 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
6035 assert(Transition && "Do not know how to promote null");
6038 /// \brief Check if we can promote \p ToBePromoted to \p Type.
6039 bool canPromote(const Instruction *ToBePromoted) const {
6040 // We could support CastInst too.
6041 return isa<BinaryOperator>(ToBePromoted);
6044 /// \brief Check if it is profitable to promote \p ToBePromoted
6045 /// by moving downward the transition through.
6046 bool shouldPromote(const Instruction *ToBePromoted) const {
6047 // Promote only if all the operands can be statically expanded.
6048 // Indeed, we do not want to introduce any new kind of transitions.
6049 for (const Use &U : ToBePromoted->operands()) {
6050 const Value *Val = U.get();
6051 if (Val == getEndOfTransition()) {
6052 // If the use is a division and the transition is on the rhs,
6053 // we cannot promote the operation, otherwise we may create a
6054 // division by zero.
6055 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6059 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6060 !isa<ConstantFP>(Val))
6063 // Check that the resulting operation is legal.
6064 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6067 return StressStoreExtract ||
6068 TLI.isOperationLegalOrCustom(
6069 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
6072 /// \brief Check whether or not \p Use can be combined
6073 /// with the transition.
6074 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6075 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6077 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
6078 void enqueueForPromotion(Instruction *ToBePromoted) {
6079 InstsToBePromoted.push_back(ToBePromoted);
6082 /// \brief Set the instruction that will be combined with the transition.
6083 void recordCombineInstruction(Instruction *ToBeCombined) {
6084 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6085 CombineInst = ToBeCombined;
6088 /// \brief Promote all the instructions enqueued for promotion if it is
6090 /// \return True if the promotion happened, false otherwise.
6092 // Check if there is something to promote.
6093 // Right now, if we do not have anything to combine with,
6094 // we assume the promotion is not profitable.
6095 if (InstsToBePromoted.empty() || !CombineInst)
6099 if (!StressStoreExtract && !isProfitableToPromote())
6103 for (auto &ToBePromoted : InstsToBePromoted)
6104 promoteImpl(ToBePromoted);
6105 InstsToBePromoted.clear();
6109 } // End of anonymous namespace.
6111 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6112 // At this point, we know that all the operands of ToBePromoted but Def
6113 // can be statically promoted.
6114 // For Def, we need to use its parameter in ToBePromoted:
6115 // b = ToBePromoted ty1 a
6116 // Def = Transition ty1 b to ty2
6117 // Move the transition down.
6118 // 1. Replace all uses of the promoted operation by the transition.
6119 // = ... b => = ... Def.
6120 assert(ToBePromoted->getType() == Transition->getType() &&
6121 "The type of the result of the transition does not match "
6123 ToBePromoted->replaceAllUsesWith(Transition);
6124 // 2. Update the type of the uses.
6125 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6126 Type *TransitionTy = getTransitionType();
6127 ToBePromoted->mutateType(TransitionTy);
6128 // 3. Update all the operands of the promoted operation with promoted
6130 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6131 for (Use &U : ToBePromoted->operands()) {
6132 Value *Val = U.get();
6133 Value *NewVal = nullptr;
6134 if (Val == Transition)
6135 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6136 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6137 isa<ConstantFP>(Val)) {
6138 // Use a splat constant if it is not safe to use undef.
6139 NewVal = getConstantVector(
6140 cast<Constant>(Val),
6141 isa<UndefValue>(Val) ||
6142 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6144 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6146 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6148 Transition->removeFromParent();
6149 Transition->insertAfter(ToBePromoted);
6150 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6153 /// Some targets can do store(extractelement) with one instruction.
6154 /// Try to push the extractelement towards the stores when the target
6155 /// has this feature and this is profitable.
6156 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
6157 unsigned CombineCost = UINT_MAX;
6158 if (DisableStoreExtract || !TLI ||
6159 (!StressStoreExtract &&
6160 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6161 Inst->getOperand(1), CombineCost)))
6164 // At this point we know that Inst is a vector to scalar transition.
6165 // Try to move it down the def-use chain, until:
6166 // - We can combine the transition with its single use
6167 // => we got rid of the transition.
6168 // - We escape the current basic block
6169 // => we would need to check that we are moving it at a cheaper place and
6170 // we do not do that for now.
6171 BasicBlock *Parent = Inst->getParent();
6172 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
6173 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
6174 // If the transition has more than one use, assume this is not going to be
6176 while (Inst->hasOneUse()) {
6177 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
6178 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
6180 if (ToBePromoted->getParent() != Parent) {
6181 DEBUG(dbgs() << "Instruction to promote is in a different block ("
6182 << ToBePromoted->getParent()->getName()
6183 << ") than the transition (" << Parent->getName() << ").\n");
6187 if (VPH.canCombine(ToBePromoted)) {
6188 DEBUG(dbgs() << "Assume " << *Inst << '\n'
6189 << "will be combined with: " << *ToBePromoted << '\n');
6190 VPH.recordCombineInstruction(ToBePromoted);
6191 bool Changed = VPH.promote();
6192 NumStoreExtractExposed += Changed;
6196 DEBUG(dbgs() << "Try promoting.\n");
6197 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6200 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
6202 VPH.enqueueForPromotion(ToBePromoted);
6203 Inst = ToBePromoted;
6208 bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
6209 // Bail out if we inserted the instruction to prevent optimizations from
6210 // stepping on each other's toes.
6211 if (InsertedInsts.count(I))
6214 if (PHINode *P = dyn_cast<PHINode>(I)) {
6215 // It is possible for very late stage optimizations (such as SimplifyCFG)
6216 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6217 // trivial PHI, go ahead and zap it here.
6218 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
6219 P->replaceAllUsesWith(V);
6220 P->eraseFromParent();
6227 if (CastInst *CI = dyn_cast<CastInst>(I)) {
6228 // If the source of the cast is a constant, then this should have
6229 // already been constant folded. The only reason NOT to constant fold
6230 // it is if something (e.g. LSR) was careful to place the constant
6231 // evaluation in a block other than then one that uses it (e.g. to hoist
6232 // the address of globals out of a loop). If this is the case, we don't
6233 // want to forward-subst the cast.
6234 if (isa<Constant>(CI->getOperand(0)))
6237 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
6240 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6241 /// Sink a zext or sext into its user blocks if the target type doesn't
6242 /// fit in one register
6244 TLI->getTypeAction(CI->getContext(),
6245 TLI->getValueType(*DL, CI->getType())) ==
6246 TargetLowering::TypeExpandInteger) {
6247 return SinkCast(CI);
6249 bool MadeChange = moveExtToFormExtLoad(I);
6250 return MadeChange | optimizeExtUses(I);
6256 if (CmpInst *CI = dyn_cast<CmpInst>(I))
6257 if (!TLI || !TLI->hasMultipleConditionRegisters())
6258 return OptimizeCmpExpression(CI);
6260 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6261 stripInvariantGroupMetadata(*LI);
6263 bool Modified = optimizeLoadExt(LI);
6264 unsigned AS = LI->getPointerAddressSpace();
6265 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6271 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6272 stripInvariantGroupMetadata(*SI);
6274 unsigned AS = SI->getPointerAddressSpace();
6275 return optimizeMemoryInst(I, SI->getOperand(1),
6276 SI->getOperand(0)->getType(), AS);
6281 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6283 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6284 BinOp->getOpcode() == Instruction::LShr)) {
6285 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6286 if (TLI && CI && TLI->hasExtractBitsInsn())
6287 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
6292 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
6293 if (GEPI->hasAllZeroIndices()) {
6294 /// The GEP operand must be a pointer, so must its result -> BitCast
6295 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6296 GEPI->getName(), GEPI);
6297 GEPI->replaceAllUsesWith(NC);
6298 GEPI->eraseFromParent();
6300 optimizeInst(NC, ModifiedDT);
6306 if (CallInst *CI = dyn_cast<CallInst>(I))
6307 return optimizeCallInst(CI, ModifiedDT);
6309 if (SelectInst *SI = dyn_cast<SelectInst>(I))
6310 return optimizeSelectInst(SI);
6312 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
6313 return optimizeShuffleVectorInst(SVI);
6315 if (auto *Switch = dyn_cast<SwitchInst>(I))
6316 return optimizeSwitchInst(Switch);
6318 if (isa<ExtractElementInst>(I))
6319 return optimizeExtractElementInst(I);
6324 /// Given an OR instruction, check to see if this is a bitreverse
6325 /// idiom. If so, insert the new intrinsic and return true.
6326 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6327 const TargetLowering &TLI) {
6328 if (!I.getType()->isIntegerTy() ||
6329 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6330 TLI.getValueType(DL, I.getType(), true)))
6333 SmallVector<Instruction*, 4> Insts;
6334 if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
6336 Instruction *LastInst = Insts.back();
6337 I.replaceAllUsesWith(LastInst);
6338 RecursivelyDeleteTriviallyDeadInstructions(&I);
6342 // In this pass we look for GEP and cast instructions that are used
6343 // across basic blocks and rewrite them to improve basic-block-at-a-time
6345 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
6347 bool MadeChange = false;
6349 CurInstIterator = BB.begin();
6350 while (CurInstIterator != BB.end()) {
6351 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6356 bool MadeBitReverse = true;
6357 while (TLI && MadeBitReverse) {
6358 MadeBitReverse = false;
6359 for (auto &I : reverse(BB)) {
6360 if (makeBitReverse(I, *DL, *TLI)) {
6361 MadeBitReverse = MadeChange = true;
6366 MadeChange |= dupRetToEnableTailCallOpts(&BB);
6371 // llvm.dbg.value is far away from the value then iSel may not be able
6372 // handle it properly. iSel will drop llvm.dbg.value if it can not
6373 // find a node corresponding to the value.
6374 bool CodeGenPrepare::placeDbgValues(Function &F) {
6375 bool MadeChange = false;
6376 for (BasicBlock &BB : F) {
6377 Instruction *PrevNonDbgInst = nullptr;
6378 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
6379 Instruction *Insn = &*BI++;
6380 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
6381 // Leave dbg.values that refer to an alloca alone. These
6382 // instrinsics describe the address of a variable (= the alloca)
6383 // being taken. They should not be moved next to the alloca
6384 // (and to the beginning of the scope), but rather stay close to
6385 // where said address is used.
6386 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
6387 PrevNonDbgInst = Insn;
6391 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6392 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
6393 // If VI is a phi in a block with an EHPad terminator, we can't insert
6395 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6397 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6398 DVI->removeFromParent();
6399 if (isa<PHINode>(VI))
6400 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6402 DVI->insertAfter(VI);
6411 // If there is a sequence that branches based on comparing a single bit
6412 // against zero that can be combined into a single instruction, and the
6413 // target supports folding these into a single instruction, sink the
6414 // mask and compare into the branch uses. Do this before OptimizeBlock ->
6415 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
6417 bool CodeGenPrepare::sinkAndCmp(Function &F) {
6418 if (!EnableAndCmpSinking)
6420 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
6422 bool MadeChange = false;
6423 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
6424 BasicBlock *BB = &*I++;
6426 // Does this BB end with the following?
6427 // %andVal = and %val, #single-bit-set
6428 // %icmpVal = icmp %andResult, 0
6429 // br i1 %cmpVal label %dest1, label %dest2"
6430 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
6431 if (!Brcc || !Brcc->isConditional())
6433 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
6434 if (!Cmp || Cmp->getParent() != BB)
6436 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
6437 if (!Zero || !Zero->isZero())
6439 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
6440 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
6442 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
6443 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
6445 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
6447 // Push the "and; icmp" for any users that are conditional branches.
6448 // Since there can only be one branch use per BB, we don't need to keep
6449 // track of which BBs we insert into.
6450 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
6454 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
6456 if (!BrccUser || !BrccUser->isConditional())
6458 BasicBlock *UserBB = BrccUser->getParent();
6459 if (UserBB == BB) continue;
6460 DEBUG(dbgs() << "found Brcc use\n");
6462 // Sink the "and; icmp" to use.
6464 BinaryOperator *NewAnd =
6465 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
6468 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
6472 DEBUG(BrccUser->getParent()->dump());
6478 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
6479 /// success, or returns false if no or invalid metadata was found.
6480 static bool extractBranchMetadata(BranchInst *BI,
6481 uint64_t &ProbTrue, uint64_t &ProbFalse) {
6482 assert(BI->isConditional() &&
6483 "Looking for probabilities on unconditional branch?");
6484 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
6485 if (!ProfileData || ProfileData->getNumOperands() != 3)
6488 const auto *CITrue =
6489 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
6490 const auto *CIFalse =
6491 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
6492 if (!CITrue || !CIFalse)
6495 ProbTrue = CITrue->getValue().getZExtValue();
6496 ProbFalse = CIFalse->getValue().getZExtValue();
6501 /// \brief Scale down both weights to fit into uint32_t.
6502 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6503 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6504 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
6505 NewTrue = NewTrue / Scale;
6506 NewFalse = NewFalse / Scale;
6509 /// \brief Some targets prefer to split a conditional branch like:
6511 /// %0 = icmp ne i32 %a, 0
6512 /// %1 = icmp ne i32 %b, 0
6513 /// %or.cond = or i1 %0, %1
6514 /// br i1 %or.cond, label %TrueBB, label %FalseBB
6516 /// into multiple branch instructions like:
6519 /// %0 = icmp ne i32 %a, 0
6520 /// br i1 %0, label %TrueBB, label %bb2
6522 /// %1 = icmp ne i32 %b, 0
6523 /// br i1 %1, label %TrueBB, label %FalseBB
6525 /// This usually allows instruction selection to do even further optimizations
6526 /// and combine the compare with the branch instruction. Currently this is
6527 /// applied for targets which have "cheap" jump instructions.
6529 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6531 bool CodeGenPrepare::splitBranchCondition(Function &F) {
6532 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
6535 bool MadeChange = false;
6536 for (auto &BB : F) {
6537 // Does this BB end with the following?
6538 // %cond1 = icmp|fcmp|binary instruction ...
6539 // %cond2 = icmp|fcmp|binary instruction ...
6540 // %cond.or = or|and i1 %cond1, cond2
6541 // br i1 %cond.or label %dest1, label %dest2"
6542 BinaryOperator *LogicOp;
6543 BasicBlock *TBB, *FBB;
6544 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6547 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6548 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6552 Value *Cond1, *Cond2;
6553 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6554 m_OneUse(m_Value(Cond2)))))
6555 Opc = Instruction::And;
6556 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6557 m_OneUse(m_Value(Cond2)))))
6558 Opc = Instruction::Or;
6562 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6563 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6566 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6569 auto *InsertBefore = std::next(Function::iterator(BB))
6570 .getNodePtrUnchecked();
6571 auto TmpBB = BasicBlock::Create(BB.getContext(),
6572 BB.getName() + ".cond.split",
6573 BB.getParent(), InsertBefore);
6575 // Update original basic block by using the first condition directly by the
6576 // branch instruction and removing the no longer needed and/or instruction.
6577 Br1->setCondition(Cond1);
6578 LogicOp->eraseFromParent();
6580 // Depending on the conditon we have to either replace the true or the false
6581 // successor of the original branch instruction.
6582 if (Opc == Instruction::And)
6583 Br1->setSuccessor(0, TmpBB);
6585 Br1->setSuccessor(1, TmpBB);
6587 // Fill in the new basic block.
6588 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6589 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6590 I->removeFromParent();
6591 I->insertBefore(Br2);
6594 // Update PHI nodes in both successors. The original BB needs to be
6595 // replaced in one succesor's PHI nodes, because the branch comes now from
6596 // the newly generated BB (NewBB). In the other successor we need to add one
6597 // incoming edge to the PHI nodes, because both branch instructions target
6598 // now the same successor. Depending on the original branch condition
6599 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6600 // we perfrom the correct update for the PHI nodes.
6601 // This doesn't change the successor order of the just created branch
6602 // instruction (or any other instruction).
6603 if (Opc == Instruction::Or)
6604 std::swap(TBB, FBB);
6606 // Replace the old BB with the new BB.
6607 for (auto &I : *TBB) {
6608 PHINode *PN = dyn_cast<PHINode>(&I);
6612 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6613 PN->setIncomingBlock(i, TmpBB);
6616 // Add another incoming edge form the new BB.
6617 for (auto &I : *FBB) {
6618 PHINode *PN = dyn_cast<PHINode>(&I);
6621 auto *Val = PN->getIncomingValueForBlock(&BB);
6622 PN->addIncoming(Val, TmpBB);
6625 // Update the branch weights (from SelectionDAGBuilder::
6626 // FindMergedConditions).
6627 if (Opc == Instruction::Or) {
6628 // Codegen X | Y as:
6637 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6638 // The requirement is that
6639 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6640 // = TrueProb for orignal BB.
6641 // Assuming the orignal weights are A and B, one choice is to set BB1's
6642 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6644 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6645 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6646 // TmpBB, but the math is more complicated.
6647 uint64_t TrueWeight, FalseWeight;
6648 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
6649 uint64_t NewTrueWeight = TrueWeight;
6650 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6651 scaleWeights(NewTrueWeight, NewFalseWeight);
6652 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6653 .createBranchWeights(TrueWeight, FalseWeight));
6655 NewTrueWeight = TrueWeight;
6656 NewFalseWeight = 2 * FalseWeight;
6657 scaleWeights(NewTrueWeight, NewFalseWeight);
6658 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6659 .createBranchWeights(TrueWeight, FalseWeight));
6662 // Codegen X & Y as:
6670 // This requires creation of TmpBB after CurBB.
6672 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6673 // The requirement is that
6674 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6675 // = FalseProb for orignal BB.
6676 // Assuming the orignal weights are A and B, one choice is to set BB1's
6677 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6679 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6680 uint64_t TrueWeight, FalseWeight;
6681 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
6682 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6683 uint64_t NewFalseWeight = FalseWeight;
6684 scaleWeights(NewTrueWeight, NewFalseWeight);
6685 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6686 .createBranchWeights(TrueWeight, FalseWeight));
6688 NewTrueWeight = 2 * TrueWeight;
6689 NewFalseWeight = FalseWeight;
6690 scaleWeights(NewTrueWeight, NewFalseWeight);
6691 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6692 .createBranchWeights(TrueWeight, FalseWeight));
6696 // Note: No point in getting fancy here, since the DT info is never
6697 // available to CodeGenPrepare.
6702 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6708 void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
6709 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
6710 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());