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 CastOp = Instruction::SExt;
334 case Type::FloatTyID:
335 case Type::DoubleTyID: {
336 CastOp = Instruction::FPToSI;
339 case Type::PointerTyID: {
340 CastOp = Instruction::PtrToInt;
346 return Builder.CreateCast(CastOp, DepVal, TargetIntegerType);
349 // Given a value, if it's a tainted address, this function returns the
350 // instruction that ORs the "dependence value" with the "original address".
351 // Otherwise, returns nullptr. This instruction is the first OR instruction
352 // where one of its operand is an AND instruction with an operand being 0.
354 // E.g., it returns '%4 = or i32 %3, %2' given 'CurrentAddress' is '%5'.
355 // %0 = load i32, i32* @y, align 4, !tbaa !1
356 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
357 // %1 = sext i1 %cmp to i32
358 // %2 = ptrtoint i32* @x to i32
359 // %3 = and i32 %1, 0
360 // %4 = or i32 %3, %2
361 // %5 = inttoptr i32 %4 to i32*
362 // store i32 1, i32* %5, align 4
363 Instruction* getOrAddress(Value* CurrentAddress) {
364 // Is it a cast from integer to pointer type.
365 Instruction* OrAddress = nullptr;
366 Instruction* AndDep = nullptr;
367 Instruction* CastToInt = nullptr;
368 Value* ActualAddress = nullptr;
369 Constant* ZeroConst = nullptr;
371 const Instruction* CastToPtr = dyn_cast<Instruction>(CurrentAddress);
372 if (CastToPtr && CastToPtr->getOpcode() == Instruction::IntToPtr) {
373 // Is it an OR instruction: %1 = or %and, %actualAddress.
374 if ((OrAddress = dyn_cast<Instruction>(CastToPtr->getOperand(0))) &&
375 OrAddress->getOpcode() == Instruction::Or) {
376 // The first operand should be and AND instruction.
377 AndDep = dyn_cast<Instruction>(OrAddress->getOperand(0));
378 if (AndDep && AndDep->getOpcode() == Instruction::And) {
379 // Also make sure its first operand of the "AND" is 0, or the "AND" is
380 // marked explicitly by "NoInstCombine".
381 if ((ZeroConst = dyn_cast<Constant>(AndDep->getOperand(1))) &&
382 ZeroConst->isNullValue()) {
388 // Looks like it's not been tainted.
392 // Given a value, if it's a tainted address, this function returns the
393 // instruction that taints the "dependence value". Otherwise, returns nullptr.
394 // This instruction is the last AND instruction where one of its operand is 0.
395 // E.g., it returns '%3' given 'CurrentAddress' is '%5'.
396 // %0 = load i32, i32* @y, align 4, !tbaa !1
397 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
398 // %1 = sext i1 %cmp to i32
399 // %2 = ptrtoint i32* @x to i32
400 // %3 = and i32 %1, 0
401 // %4 = or i32 %3, %2
402 // %5 = inttoptr i32 %4 to i32*
403 // store i32 1, i32* %5, align 4
404 Instruction* getAndDependence(Value* CurrentAddress) {
405 // If 'CurrentAddress' is tainted, get the OR instruction.
406 auto* OrAddress = getOrAddress(CurrentAddress);
407 if (OrAddress == nullptr) {
411 // No need to check the operands.
412 auto* AndDepInst = dyn_cast<Instruction>(OrAddress->getOperand(0));
417 // Given a value, if it's a tainted address, this function returns
418 // the "dependence value", which is the first operand in the AND instruction.
419 // E.g., it returns '%1' given 'CurrentAddress' is '%5'.
420 // %0 = load i32, i32* @y, align 4, !tbaa !1
421 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
422 // %1 = sext i1 %cmp to i32
423 // %2 = ptrtoint i32* @x to i32
424 // %3 = and i32 %1, 0
425 // %4 = or i32 %3, %2
426 // %5 = inttoptr i32 %4 to i32*
427 // store i32 1, i32* %5, align 4
428 Value* getDependence(Value* CurrentAddress) {
429 auto* AndInst = getAndDependence(CurrentAddress);
430 if (AndInst == nullptr) {
433 return AndInst->getOperand(0);
436 // Given an address that has been tainted, returns the only condition it depends
437 // on, if any; otherwise, returns nullptr.
438 Value* getConditionDependence(Value* Address) {
439 auto* Dep = getDependence(Address);
440 if (Dep == nullptr) {
441 // 'Address' has not been dependence-tainted.
445 Value* Operand = Dep;
447 auto* Inst = dyn_cast<Instruction>(Operand);
448 if (Inst == nullptr) {
449 // Non-instruction type does not have condition dependence.
452 if (Inst->getOpcode() == Instruction::ICmp) {
455 if (Inst->getNumOperands() != 1) {
458 Operand = Inst->getOperand(0);
464 // Conservatively decides whether the dependence set of 'Val1' includes the
465 // dependence set of 'Val2'. If 'ExpandSecondValue' is false, we do not expand
466 // 'Val2' and use that single value as its dependence set.
467 // If it returns true, it means the dependence set of 'Val1' includes that of
468 // 'Val2'; otherwise, it only means we cannot conclusively decide it.
469 bool dependenceSetInclusion(Value* Val1, Value* Val2,
470 int Val1ExpandLevel = 2 * kDependenceDepth,
471 int Val2ExpandLevel = kDependenceDepth) {
472 typedef SmallSet<Value*, 8> IncludingSet;
473 typedef SmallSet<Value*, 4> IncludedSet;
475 IncludingSet DepSet1;
477 // Look for more depths for the including set.
478 recursivelyFindDependence(&DepSet1, Val1, false /*Insert all visited nodes*/,
480 recursivelyFindDependence(&DepSet2, Val2, true /*Only insert leaf nodes*/,
483 auto set_inclusion = [](IncludingSet FullSet, IncludedSet Subset) {
484 for (auto* Dep : Subset) {
485 if (0 == FullSet.count(Dep)) {
491 bool inclusion = set_inclusion(DepSet1, DepSet2);
492 DEBUG(dbgs() << "[dependenceSetInclusion]: " << inclusion << "\n");
493 DEBUG(dbgs() << "Including set for: " << *Val1 << "\n");
494 DEBUG(for (const auto* Dep : DepSet1) { dbgs() << "\t\t" << *Dep << "\n"; });
495 DEBUG(dbgs() << "Included set for: " << *Val2 << "\n");
496 DEBUG(for (const auto* Dep : DepSet2) { dbgs() << "\t\t" << *Dep << "\n"; });
501 // Recursively iterates through the operands spawned from 'DepVal'. If there
502 // exists a single value that 'DepVal' only depends on, we call that value the
503 // root dependence of 'DepVal' and return it. Otherwise, return 'DepVal'.
504 Value* getRootDependence(Value* DepVal) {
505 SmallSet<Value*, 8> DepSet;
506 for (unsigned depth = kDependenceDepth; depth > 0; --depth) {
507 recursivelyFindDependence(&DepSet, DepVal, true /*Only insert leaf nodes*/,
509 if (DepSet.size() == 1) {
510 return *DepSet.begin();
517 // This function actually taints 'DepVal' to the address to 'SI'. If the
519 // of 'SI' already depends on whatever 'DepVal' depends on, this function
520 // doesn't do anything and returns false. Otherwise, returns true.
522 // This effect forces the store and any stores that comes later to depend on
523 // 'DepVal'. For example, we have a condition "cond", and a store instruction
524 // "s: STORE addr, val". If we want "s" (and any later store) to depend on
525 // "cond", we do the following:
526 // %conv = sext i1 %cond to i32
527 // %addrVal = ptrtoint i32* %addr to i32
528 // %andCond = and i32 conv, 0;
529 // %orAddr = or i32 %andCond, %addrVal;
530 // %NewAddr = inttoptr i32 %orAddr to i32*;
532 // This is a more concrete example:
534 // %0 = load i32, i32* @y, align 4, !tbaa !1
535 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
536 // %1 = sext i1 %cmp to i32
537 // %2 = ptrtoint i32* @x to i32
538 // %3 = and i32 %1, 0
539 // %4 = or i32 %3, %2
540 // %5 = inttoptr i32 %4 to i32*
541 // store i32 1, i32* %5, align 4
542 bool taintStoreAddress(StoreInst* SI, Value* DepVal) {
543 // Set the insertion point right after the 'DepVal'.
544 Instruction* Inst = nullptr;
545 IRBuilder<true, NoFolder> Builder(SI);
546 BasicBlock* BB = SI->getParent();
547 Value* Address = SI->getPointerOperand();
548 Type* TargetIntegerType =
549 IntegerType::get(Address->getContext(),
550 BB->getModule()->getDataLayout().getPointerSizeInBits());
552 // Does SI's address already depends on whatever 'DepVal' depends on?
553 if (StoreAddressDependOnValue(SI, DepVal)) {
557 // Figure out if there's a root variable 'DepVal' depends on. For example, we
558 // can extract "getelementptr inbounds %struct, %struct* %0, i64 0, i32 123"
559 // to be "%struct* %0" since all other operands are constant.
560 auto* RootVal = getRootDependence(DepVal);
561 auto* RootInst = dyn_cast<Instruction>(RootVal);
562 auto* DepValInst = dyn_cast<Instruction>(DepVal);
563 if (RootInst && DepValInst &&
564 RootInst->getParent() == DepValInst->getParent()) {
568 // Is this already a dependence-tainted store?
569 Value* OldDep = getDependence(Address);
571 // The address of 'SI' has already been tainted. Just need to absorb the
572 // DepVal to the existing dependence in the address of SI.
573 Instruction* AndDep = getAndDependence(Address);
574 IRBuilder<true, NoFolder> Builder(AndDep);
575 Value* NewDep = nullptr;
576 if (DepVal->getType() == AndDep->getType()) {
577 NewDep = Builder.CreateAnd(OldDep, DepVal);
579 NewDep = Builder.CreateAnd(
580 OldDep, createCast(Builder, DepVal, TargetIntegerType));
583 auto* NewDepInst = dyn_cast<Instruction>(NewDep);
585 // Use the new AND instruction as the dependence
586 AndDep->setOperand(0, NewDep);
590 // SI's address has not been tainted. Now taint it with 'DepVal'.
591 Value* CastDepToInt = createCast(Builder, DepVal, TargetIntegerType);
592 Value* PtrToIntCast = Builder.CreatePtrToInt(Address, TargetIntegerType);
594 Builder.CreateAnd(CastDepToInt, ConstantInt::get(TargetIntegerType, 0));
595 auto AndInst = dyn_cast<Instruction>(AndDepVal);
596 // XXX-comment: The original IR InstCombiner would change our and instruction
597 // to a select and then the back end optimize the condition out. We attach a
598 // flag to instructions and set it here to inform the InstCombiner to not to
599 // touch this and instruction at all.
600 Value* OrAddr = Builder.CreateOr(AndDepVal, PtrToIntCast);
601 Value* NewAddr = Builder.CreateIntToPtr(OrAddr, Address->getType());
603 DEBUG(dbgs() << "[taintStoreAddress]\n"
604 << "Original store: " << *SI << '\n');
605 SI->setOperand(1, NewAddr);
608 DEBUG(dbgs() << "\tTargetIntegerType: " << *TargetIntegerType << '\n'
609 << "\tCast dependence value to integer: " << *CastDepToInt
611 << "\tCast address to integer: " << *PtrToIntCast << '\n'
612 << "\tAnd dependence value: " << *AndDepVal << '\n'
613 << "\tOr address: " << *OrAddr << '\n'
614 << "\tCast or instruction to address: " << *NewAddr << "\n\n");
619 // Looks for the previous store in the if block --- 'BrBB', which makes the
620 // speculative store 'StoreToHoist' safe.
621 Value* getSpeculativeStoreInPrevBB(StoreInst* StoreToHoist, BasicBlock* BrBB) {
622 assert(StoreToHoist && "StoreToHoist must be a real store");
624 Value* StorePtr = StoreToHoist->getPointerOperand();
626 // Look for a store to the same pointer in BrBB.
627 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), RE = BrBB->rend();
629 Instruction* CurI = &*RI;
631 StoreInst* SI = dyn_cast<StoreInst>(CurI);
632 // Found the previous store make sure it stores to the same location.
633 // XXX-update: If the previous store's original untainted address are the
634 // same as 'StorePtr', we are also good to hoist the store.
635 if (SI && (SI->getPointerOperand() == StorePtr ||
636 GetUntaintedAddress(SI->getPointerOperand()) == StorePtr)) {
637 // Found the previous store, return its value operand.
643 "We should not reach here since this store is safe to speculate");
646 // XXX-comment: Returns true if it changes the code, false otherwise (the branch
647 // condition already depends on 'DepVal'.
648 bool taintConditionalBranch(BranchInst* BI, Value* DepVal) {
649 assert(BI->isConditional());
650 auto* Cond = BI->getOperand(0);
651 if (dependenceSetInclusion(Cond, DepVal)) {
652 // The dependence/ordering is self-evident.
656 IRBuilder<true, NoFolder> Builder(BI);
658 Builder.CreateAnd(DepVal, ConstantInt::get(DepVal->getType(), 0));
660 Builder.CreateTrunc(AndDep, IntegerType::get(DepVal->getContext(), 1));
661 auto* OrCond = Builder.CreateOr(TruncAndDep, Cond);
662 BI->setOperand(0, OrCond);
665 DEBUG(dbgs() << "\tTainted branch condition:\n" << *BI->getParent());
670 bool ConditionalBranchDependsOnValue(BranchInst* BI, Value* DepVal) {
671 assert(BI->isConditional());
672 auto* Cond = BI->getOperand(0);
673 return dependenceSetInclusion(Cond, DepVal);
676 // XXX-update: For a relaxed load 'LI', find the first immediate atomic store or
677 // the first conditional branch. Returns nullptr if there's no such immediately
678 // following store/branch instructions, which we can only enforce the load with
679 // 'acquire'. 'ChainedBB' contains all the blocks chained together with
680 // unconditional branches from 'BB' to the block with the first store/cond
682 template <typename Vector>
683 Instruction* findFirstStoreCondBranchInst(LoadInst* LI, Vector* ChainedBB) {
684 // In some situations, relaxed loads can be left as is:
685 // 1. The relaxed load is used to calculate the address of the immediate
687 // 2. The relaxed load is used as a condition in the immediate following
688 // condition, and there are no stores in between. This is actually quite
690 // int r1 = x.load(relaxed);
692 // y.store(1, relaxed);
694 // However, in this function, we don't deal with them directly. Instead, we
695 // just find the immediate following store/condition branch and return it.
697 assert(ChainedBB != nullptr && "Chained BB should not be nullptr");
698 auto* BB = LI->getParent();
699 ChainedBB->push_back(BB);
701 auto BBI = BasicBlock::iterator(LI);
704 for (; BBI != BE; BBI++) {
705 auto* Inst = dyn_cast<Instruction>(&*BBI);
706 if (Inst == nullptr) {
709 if (Inst->getOpcode() == Instruction::Store) {
711 } else if (Inst->getOpcode() == Instruction::Br) {
712 auto* BrInst = dyn_cast<BranchInst>(Inst);
713 if (BrInst->isConditional()) {
716 // Reinitialize iterators with the destination of the unconditional
718 BB = BrInst->getSuccessor(0);
719 ChainedBB->push_back(BB);
732 // XXX-comment: Returns whether the code has been changed.
733 bool taintMonotonicLoads(const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
734 bool Changed = false;
735 for (auto* LI : MonotonicLoadInsts) {
736 SmallVector<BasicBlock*, 2> ChainedBB;
737 auto* FirstInst = findFirstStoreCondBranchInst(LI, &ChainedBB);
738 if (FirstInst == nullptr) {
739 // We don't seem to be able to taint a following store/conditional branch
740 // instruction. Simply make it acquire.
741 DEBUG(dbgs() << "[RelaxedLoad]: Transformed to acquire load\n"
743 LI->setOrdering(Acquire);
747 // Taint 'FirstInst', which could be a store or a condition branch
749 if (FirstInst->getOpcode() == Instruction::Store) {
750 Changed |= taintStoreAddress(dyn_cast<StoreInst>(FirstInst), LI);
751 } else if (FirstInst->getOpcode() == Instruction::Br) {
752 Changed |= taintConditionalBranch(dyn_cast<BranchInst>(FirstInst), LI);
754 assert(false && "findFirstStoreCondBranchInst() should return a "
755 "store/condition branch instruction");
761 // Inserts a fake conditional branch right after the instruction 'SplitInst',
762 // and the branch condition is 'Condition'. 'SplitInst' will be placed in the
763 // newly created block.
764 void AddFakeConditionalBranch(Instruction* SplitInst, Value* Condition) {
765 auto* BB = SplitInst->getParent();
766 TerminatorInst* ThenTerm = nullptr;
767 TerminatorInst* ElseTerm = nullptr;
768 SplitBlockAndInsertIfThenElse(Condition, SplitInst, &ThenTerm, &ElseTerm);
769 assert(ThenTerm && ElseTerm &&
770 "Then/Else terminators cannot be empty after basic block spliting");
771 auto* ThenBB = ThenTerm->getParent();
772 auto* ElseBB = ElseTerm->getParent();
773 auto* TailBB = ThenBB->getSingleSuccessor();
774 assert(TailBB && "Tail block cannot be empty after basic block spliting");
776 ThenBB->disableCanEliminateBlock();
777 ThenBB->disableCanEliminateBlock();
778 TailBB->disableCanEliminateBlock();
779 ThenBB->setName(BB->getName() + "Then.Fake");
780 ElseBB->setName(BB->getName() + "Else.Fake");
781 DEBUG(dbgs() << "Add fake conditional branch:\n"
783 << *ThenBB << "Else Block:\n"
787 // Returns true if the code is changed, and false otherwise.
788 void TaintRelaxedLoads(Instruction* UsageInst, Instruction* InsertPoint) {
789 // For better performance, we can add a "AND X 0" instruction before the
791 auto* BB = UsageInst->getParent();
792 if (InsertPoint == nullptr) {
793 InsertPoint = UsageInst->getNextNode();
795 // Insert instructions after PHI nodes.
796 while (dyn_cast<PHINode>(InsertPoint)) {
797 InsertPoint = InsertPoint->getNextNode();
799 // First thing is to cast 'UsageInst' to an integer type if necessary.
800 Value* AndTarget = nullptr;
801 Type* TargetIntegerType =
802 IntegerType::get(UsageInst->getContext(),
803 BB->getModule()->getDataLayout().getPointerSizeInBits());
804 if (UsageInst->getType() == TargetIntegerType) {
805 AndTarget = UsageInst;
807 IRBuilder<true, NoFolder> Builder(InsertPoint);
808 AndTarget = createCast(Builder, UsageInst, TargetIntegerType);
811 // Check whether InsertPoint is a added fake conditional branch.
812 BranchInst* BI = nullptr;
813 if ((BI = dyn_cast<BranchInst>(InsertPoint)) && BI->isConditional()) {
814 auto* Cond = dyn_cast<Instruction>(BI->getOperand(0));
815 if (Cond && Cond->getOpcode() == Instruction::ICmp) {
816 auto* CmpInst = dyn_cast<ICmpInst>(Cond);
817 auto* Op0 = dyn_cast<Instruction>(Cond->getOperand(0));
818 auto* Op1 = dyn_cast<ConstantInt>(Cond->getOperand(1));
820 // %cmp = ICMP_NE %tmp, 0
823 // %tmp1 = And X, NewTaintedVal
824 // %tmp2 = And %tmp1, 0
825 // %cmp = ICMP_NE %tmp2, 0
827 if (CmpInst && CmpInst->getPredicate() == CmpInst::ICMP_NE && Op0 &&
828 Op0->getOpcode() == Instruction::And && Op1 && Op1->isZero()) {
829 auto* Op01 = dyn_cast<ConstantInt>(Op0->getOperand(1));
830 if (Op01 && Op01->isZero()) {
831 // Now we have a previously added fake cond branch.
832 auto* Op00 = Op0->getOperand(0);
833 IRBuilder<true, NoFolder> Builder(CmpInst);
834 AndTarget = Builder.CreateAnd(Op00, AndTarget);
835 auto* AndZero = dyn_cast<Instruction>(Builder.CreateAnd(
836 AndTarget, Constant::getNullValue(AndTarget->getType())));
837 CmpInst->setOperand(0, AndZero);
844 IRBuilder<true, NoFolder> Builder(InsertPoint);
845 auto* AndZero = dyn_cast<Instruction>(
846 Builder.CreateAnd(AndTarget, Constant::getNullValue(AndTarget->getType())));
847 auto* FakeCondition = dyn_cast<Instruction>(Builder.CreateICmp(
848 CmpInst::ICMP_NE, AndZero, Constant::getNullValue(AndTarget->getType())));
849 AddFakeConditionalBranch(FakeCondition->getNextNode(), FakeCondition);
852 // XXX-comment: Finds the appropriate Value derived from an atomic load.
853 // 'ChainedBB' contains all the blocks chained together with unconditional
854 // branches from LI's parent BB to the block with the first store/cond branch.
855 // If we don't find any, it means 'LI' is not used at all (which should not
856 // happen in practice). We can simply set 'LI' to be acquire just to be safe.
857 template <typename Vector>
858 Instruction* findMostRecentDependenceUsage(LoadInst* LI, Instruction* LaterInst,
861 typedef SmallSet<Instruction*, 8> UsageSet;
862 typedef DenseMap<BasicBlock*, std::unique_ptr<UsageSet>> UsageMap;
863 assert(ChainedBB->size() >= 1 && "ChainedBB must have >=1 size");
864 // Mapping from basic block in 'ChainedBB' to the set of dependence usage of
865 // 'LI' in each block.
867 auto* LoadBB = LI->getParent();
868 usage_map[LoadBB] = make_unique<UsageSet>();
869 usage_map[LoadBB]->insert(LI);
871 for (auto* BB : *ChainedBB) {
872 if (usage_map[BB] == nullptr) {
873 usage_map[BB] = make_unique<UsageSet>();
875 auto& usage_set = usage_map[BB];
876 if (usage_set->size() == 0) {
877 // The value has not been used.
880 // Calculate the usage in the current BB first.
881 std::list<Value*> bb_usage_list;
882 std::copy(usage_set->begin(), usage_set->end(),
883 std::back_inserter(bb_usage_list));
884 for (auto list_iter = bb_usage_list.begin();
885 list_iter != bb_usage_list.end(); list_iter++) {
886 auto* val = *list_iter;
887 for (auto* U : val->users()) {
888 Instruction* Inst = nullptr;
889 if (!(Inst = dyn_cast<Instruction>(U))) {
892 assert(Inst && "Usage value must be an instruction");
894 std::find(ChainedBB->begin(), ChainedBB->end(), Inst->getParent());
895 if (iter == ChainedBB->end()) {
896 // Only care about usage within ChainedBB.
899 auto* UsageBB = *iter;
902 if (!usage_set->count(Inst)) {
903 bb_usage_list.push_back(Inst);
904 usage_set->insert(Inst);
908 if (usage_map[UsageBB] == nullptr) {
909 usage_map[UsageBB] = make_unique<UsageSet>();
911 usage_map[UsageBB]->insert(Inst);
917 // Pick one usage that is in LaterInst's block and that dominates 'LaterInst'.
918 auto* LaterBB = LaterInst->getParent();
919 auto& usage_set = usage_map[LaterBB];
920 Instruction* usage_inst = nullptr;
921 for (auto* inst : *usage_set) {
922 if (DT->dominates(inst, LaterInst)) {
928 assert(usage_inst && "The usage instruction in the same block but after the "
929 "later instruction");
933 // XXX-comment: Returns whether the code has been changed.
934 bool AddFakeConditionalBranchAfterMonotonicLoads(
935 SmallSet<LoadInst*, 1>& MonotonicLoadInsts, DominatorTree* DT) {
936 bool Changed = false;
937 while (!MonotonicLoadInsts.empty()) {
938 auto* LI = *MonotonicLoadInsts.begin();
939 MonotonicLoadInsts.erase(LI);
940 SmallVector<BasicBlock*, 2> ChainedBB;
941 auto* FirstInst = findFirstStoreCondBranchInst(LI, &ChainedBB);
942 if (FirstInst != nullptr) {
943 if (FirstInst->getOpcode() == Instruction::Store) {
944 if (StoreAddressDependOnValue(dyn_cast<StoreInst>(FirstInst), LI)) {
947 } else if (FirstInst->getOpcode() == Instruction::Br) {
948 if (ConditionalBranchDependsOnValue(dyn_cast<BranchInst>(FirstInst),
953 dbgs() << "FirstInst=" << *FirstInst << "\n";
954 assert(false && "findFirstStoreCondBranchInst() should return a "
955 "store/condition branch instruction");
959 // We really need to process the relaxed load now.
960 StoreInst* SI = nullptr;;
961 if (FirstInst && (SI = dyn_cast<StoreInst>(FirstInst))) {
962 // For immediately coming stores, taint the address of the store.
963 if (SI->getParent() == LI->getParent() || DT->dominates(LI, SI)) {
964 TaintRelaxedLoads(LI, SI);
968 findMostRecentDependenceUsage(LI, FirstInst, &ChainedBB, DT);
970 LI->setOrdering(Acquire);
973 TaintRelaxedLoads(Inst, SI);
978 // No upcoming branch
980 TaintRelaxedLoads(LI, nullptr);
983 // For immediately coming branch, directly add a fake branch.
984 if (FirstInst->getParent() == LI->getParent() ||
985 DT->dominates(LI, FirstInst)) {
986 TaintRelaxedLoads(LI, FirstInst);
990 findMostRecentDependenceUsage(LI, FirstInst, &ChainedBB, DT);
992 TaintRelaxedLoads(Inst, FirstInst);
994 LI->setOrdering(Acquire);
1004 /**** Implementations of public methods for dependence tainting ****/
1005 Value* GetUntaintedAddress(Value* CurrentAddress) {
1006 auto* OrAddress = getOrAddress(CurrentAddress);
1007 if (OrAddress == nullptr) {
1008 // Is it tainted by a select instruction?
1009 auto* Inst = dyn_cast<Instruction>(CurrentAddress);
1010 if (nullptr != Inst && Inst->getOpcode() == Instruction::Select) {
1011 // A selection instruction.
1012 if (Inst->getOperand(1) == Inst->getOperand(2)) {
1013 return Inst->getOperand(1);
1017 return CurrentAddress;
1019 Value* ActualAddress = nullptr;
1021 auto* CastToInt = dyn_cast<Instruction>(OrAddress->getOperand(1));
1022 if (CastToInt && CastToInt->getOpcode() == Instruction::PtrToInt) {
1023 return CastToInt->getOperand(0);
1025 // This should be a IntToPtr constant expression.
1026 ConstantExpr* PtrToIntExpr =
1027 dyn_cast<ConstantExpr>(OrAddress->getOperand(1));
1028 if (PtrToIntExpr && PtrToIntExpr->getOpcode() == Instruction::PtrToInt) {
1029 return PtrToIntExpr->getOperand(0);
1033 // Looks like it's not been dependence-tainted. Returns itself.
1034 return CurrentAddress;
1037 MemoryLocation GetUntaintedMemoryLocation(StoreInst* SI) {
1039 SI->getAAMetadata(AATags);
1040 const auto& DL = SI->getModule()->getDataLayout();
1041 const auto* OriginalAddr = GetUntaintedAddress(SI->getPointerOperand());
1042 DEBUG(if (OriginalAddr != SI->getPointerOperand()) {
1043 dbgs() << "[GetUntaintedMemoryLocation]\n"
1044 << "Storing address: " << *SI->getPointerOperand()
1045 << "\nUntainted address: " << *OriginalAddr << "\n";
1047 return MemoryLocation(OriginalAddr,
1048 DL.getTypeStoreSize(SI->getValueOperand()->getType()),
1052 bool TaintDependenceToStore(StoreInst* SI, Value* DepVal) {
1053 if (dependenceSetInclusion(SI, DepVal)) {
1057 bool tainted = taintStoreAddress(SI, DepVal);
1062 bool TaintDependenceToStoreAddress(StoreInst* SI, Value* DepVal) {
1063 if (dependenceSetInclusion(SI->getPointerOperand(), DepVal)) {
1067 bool tainted = taintStoreAddress(SI, DepVal);
1072 bool CompressTaintedStore(BasicBlock* BB) {
1073 // This function looks for windows of adajcent stores in 'BB' that satisfy the
1074 // following condition (and then do optimization):
1075 // *Addr(d1) = v1, d1 is a condition and is the only dependence the store's
1076 // address depends on && Dep(v1) includes Dep(d1);
1077 // *Addr(d2) = v2, d2 is a condition and is the only dependnece the store's
1078 // address depends on && Dep(v2) includes Dep(d2) &&
1079 // Dep(d2) includes Dep(d1);
1081 // *Addr(dN) = vN, dN is a condition and is the only dependence the store's
1082 // address depends on && Dep(dN) includes Dep(d"N-1").
1084 // As a result, Dep(dN) includes [Dep(d1) V ... V Dep(d"N-1")], so we can
1085 // safely transform the above to the following. In between these stores, we
1086 // can omit untainted stores to the same address 'Addr' since they internally
1087 // have dependence on the previous stores on the same address.
1092 for (auto BI = BB->begin(), BE = BB->end(); BI != BE; BI++) {
1093 // Look for the first store in such a window of adajacent stores.
1094 auto* FirstSI = dyn_cast<StoreInst>(&*BI);
1099 // The first store in the window must be tainted.
1100 auto* UntaintedAddress = GetUntaintedAddress(FirstSI->getPointerOperand());
1101 if (UntaintedAddress == FirstSI->getPointerOperand()) {
1105 // The first store's address must directly depend on and only depend on a
1107 auto* FirstSIDepCond = getConditionDependence(FirstSI->getPointerOperand());
1108 if (nullptr == FirstSIDepCond) {
1112 // Dep(first store's storing value) includes Dep(tainted dependence).
1113 if (!dependenceSetInclusion(FirstSI->getValueOperand(), FirstSIDepCond)) {
1117 // Look for subsequent stores to the same address that satisfy the condition
1118 // of "compressing the dependence".
1119 SmallVector<StoreInst*, 8> AdajacentStores;
1120 AdajacentStores.push_back(FirstSI);
1121 auto BII = BasicBlock::iterator(FirstSI);
1122 for (BII++; BII != BE; BII++) {
1123 auto* CurrSI = dyn_cast<StoreInst>(&*BII);
1125 if (BII->mayHaveSideEffects()) {
1126 // Be conservative. Instructions with side effects are similar to
1133 auto* OrigAddress = GetUntaintedAddress(CurrSI->getPointerOperand());
1134 auto* CurrSIDepCond = getConditionDependence(CurrSI->getPointerOperand());
1135 // All other stores must satisfy either:
1136 // A. 'CurrSI' is an untainted store to the same address, or
1137 // B. the combination of the following 5 subconditions:
1139 // 2. Untainted address is the same as the group's address;
1140 // 3. The address is tainted with a sole value which is a condition;
1141 // 4. The storing value depends on the condition in 3.
1142 // 5. The condition in 3 depends on the previous stores dependence
1145 // Condition A. Should ignore this store directly.
1146 if (OrigAddress == CurrSI->getPointerOperand() &&
1147 OrigAddress == UntaintedAddress) {
1150 // Check condition B.
1151 Value* Cond = nullptr;
1152 if (OrigAddress == CurrSI->getPointerOperand() ||
1153 OrigAddress != UntaintedAddress || CurrSIDepCond == nullptr ||
1154 !dependenceSetInclusion(CurrSI->getValueOperand(), CurrSIDepCond)) {
1155 // Check condition 1, 2, 3 & 4.
1159 // Check condition 5.
1160 StoreInst* PrevSI = AdajacentStores[AdajacentStores.size() - 1];
1161 auto* PrevSIDepCond = getConditionDependence(PrevSI->getPointerOperand());
1162 assert(PrevSIDepCond &&
1163 "Store in the group must already depend on a condtion");
1164 if (!dependenceSetInclusion(CurrSIDepCond, PrevSIDepCond)) {
1168 AdajacentStores.push_back(CurrSI);
1171 if (AdajacentStores.size() == 1) {
1172 // The outer loop should keep looking from the next store.
1176 // Now we have such a group of tainted stores to the same address.
1177 DEBUG(dbgs() << "[CompressTaintedStore]\n");
1178 DEBUG(dbgs() << "Original BB\n");
1179 DEBUG(dbgs() << *BB << '\n');
1180 auto* LastSI = AdajacentStores[AdajacentStores.size() - 1];
1181 for (unsigned i = 0; i < AdajacentStores.size() - 1; ++i) {
1182 auto* SI = AdajacentStores[i];
1184 // Use the original address for stores before the last one.
1185 SI->setOperand(1, UntaintedAddress);
1187 DEBUG(dbgs() << "Store address has been reversed: " << *SI << '\n';);
1189 // XXX-comment: Try to make the last store use fewer registers.
1190 // If LastSI's storing value is a select based on the condition with which
1191 // its address is tainted, transform the tainted address to a select
1192 // instruction, as follows:
1193 // r1 = Select Cond ? A : B
1198 // r1 = Select Cond ? A : B
1199 // r2 = Select Cond ? Addr : Addr
1201 // The idea is that both Select instructions depend on the same condition,
1202 // so hopefully the backend can generate two cmov instructions for them (and
1203 // this saves the number of registers needed).
1204 auto* LastSIDep = getConditionDependence(LastSI->getPointerOperand());
1205 auto* LastSIValue = dyn_cast<Instruction>(LastSI->getValueOperand());
1206 if (LastSIValue && LastSIValue->getOpcode() == Instruction::Select &&
1207 LastSIValue->getOperand(0) == LastSIDep) {
1208 // XXX-comment: Maybe it's better for us to just leave it as an and/or
1209 // dependence pattern.
1211 IRBuilder<true, NoFolder> Builder(LastSI);
1213 Builder.CreateSelect(LastSIDep, UntaintedAddress, UntaintedAddress);
1214 LastSI->setOperand(1, Address);
1215 DEBUG(dbgs() << "The last store becomes :" << *LastSI << "\n\n";);
1223 bool PassDependenceToStore(Value* OldAddress, StoreInst* NewStore) {
1224 Value* OldDep = getDependence(OldAddress);
1225 // Return false when there's no dependence to pass from the OldAddress.
1230 // No need to pass the dependence to NewStore's address if it already depends
1231 // on whatever 'OldAddress' depends on.
1232 if (StoreAddressDependOnValue(NewStore, OldDep)) {
1235 return taintStoreAddress(NewStore, OldAddress);
1238 SmallSet<Value*, 8> FindDependence(Value* Val) {
1239 SmallSet<Value*, 8> DepSet;
1240 recursivelyFindDependence(&DepSet, Val, true /*Only insert leaf nodes*/);
1244 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal) {
1245 return dependenceSetInclusion(SI->getPointerOperand(), DepVal);
1248 bool StoreDependOnValue(StoreInst* SI, Value* Dep) {
1249 return dependenceSetInclusion(SI, Dep);
1256 bool CodeGenPrepare::runOnFunction(Function &F) {
1257 bool EverMadeChange = false;
1259 if (skipOptnoneFunction(F))
1262 DL = &F.getParent()->getDataLayout();
1264 // Clear per function information.
1265 InsertedInsts.clear();
1266 PromotedInsts.clear();
1270 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
1271 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1272 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1273 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1274 OptSize = F.optForSize();
1276 /// This optimization identifies DIV instructions that can be
1277 /// profitably bypassed and carried out with a shorter, faster divide.
1278 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
1279 const DenseMap<unsigned int, unsigned int> &BypassWidths =
1280 TLI->getBypassSlowDivWidths();
1281 BasicBlock* BB = &*F.begin();
1282 while (BB != nullptr) {
1283 // bypassSlowDivision may create new BBs, but we don't want to reapply the
1284 // optimization to those blocks.
1285 BasicBlock* Next = BB->getNextNode();
1286 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
1291 // Eliminate blocks that contain only PHI nodes and an
1292 // unconditional branch.
1293 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
1295 // llvm.dbg.value is far away from the value then iSel may not be able
1296 // handle it properly. iSel will drop llvm.dbg.value if it can not
1297 // find a node corresponding to the value.
1298 EverMadeChange |= placeDbgValues(F);
1300 // If there is a mask, compare against zero, and branch that can be combined
1301 // into a single target instruction, push the mask and compare into branch
1302 // users. Do this before OptimizeBlock -> OptimizeInst ->
1303 // OptimizeCmpExpression, which perturbs the pattern being searched for.
1304 if (!DisableBranchOpts) {
1305 EverMadeChange |= sinkAndCmp(F);
1306 EverMadeChange |= splitBranchCondition(F);
1309 bool MadeChange = true;
1310 while (MadeChange) {
1312 for (Function::iterator I = F.begin(); I != F.end(); ) {
1313 BasicBlock *BB = &*I++;
1314 bool ModifiedDTOnIteration = false;
1315 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
1317 // Restart BB iteration if the dominator tree of the Function was changed
1318 if (ModifiedDTOnIteration)
1321 EverMadeChange |= MadeChange;
1326 if (!DisableBranchOpts) {
1328 SmallPtrSet<BasicBlock*, 8> WorkList;
1329 for (BasicBlock &BB : F) {
1330 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
1331 MadeChange |= ConstantFoldTerminator(&BB, true);
1332 if (!MadeChange) continue;
1334 for (SmallVectorImpl<BasicBlock*>::iterator
1335 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1336 if (pred_begin(*II) == pred_end(*II))
1337 WorkList.insert(*II);
1340 // Delete the dead blocks and any of their dead successors.
1341 MadeChange |= !WorkList.empty();
1342 while (!WorkList.empty()) {
1343 BasicBlock *BB = *WorkList.begin();
1345 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
1347 DeleteDeadBlock(BB);
1349 for (SmallVectorImpl<BasicBlock*>::iterator
1350 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1351 if (pred_begin(*II) == pred_end(*II))
1352 WorkList.insert(*II);
1355 // Merge pairs of basic blocks with unconditional branches, connected by
1357 if (EverMadeChange || MadeChange)
1358 MadeChange |= eliminateFallThrough(F);
1360 EverMadeChange |= MadeChange;
1363 if (!DisableGCOpts) {
1364 SmallVector<Instruction *, 2> Statepoints;
1365 for (BasicBlock &BB : F)
1366 for (Instruction &I : BB)
1367 if (isStatepoint(I))
1368 Statepoints.push_back(&I);
1369 for (auto &I : Statepoints)
1370 EverMadeChange |= simplifyOffsetableRelocate(*I);
1373 // XXX-comment: Delay dealing with relaxed loads in this function to avoid
1374 // further changes done by other passes (e.g., SimplifyCFG).
1375 // Collect all the relaxed loads.
1376 SmallSet<LoadInst*, 1> MonotonicLoadInsts;
1377 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
1378 if (I->isAtomic()) {
1379 switch (I->getOpcode()) {
1380 case Instruction::Load: {
1381 auto* LI = dyn_cast<LoadInst>(&*I);
1382 if (LI->getOrdering() == Monotonic) {
1383 MonotonicLoadInsts.insert(LI);
1394 AddFakeConditionalBranchAfterMonotonicLoads(MonotonicLoadInsts, DT);
1396 return EverMadeChange;
1399 /// Merge basic blocks which are connected by a single edge, where one of the
1400 /// basic blocks has a single successor pointing to the other basic block,
1401 /// which has a single predecessor.
1402 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
1403 bool Changed = false;
1404 // Scan all of the blocks in the function, except for the entry block.
1405 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1406 BasicBlock *BB = &*I++;
1407 // If the destination block has a single pred, then this is a trivial
1408 // edge, just collapse it.
1409 BasicBlock *SinglePred = BB->getSinglePredecessor();
1411 // Don't merge if BB's address is taken.
1412 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
1414 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
1415 if (Term && !Term->isConditional()) {
1417 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
1418 // Remember if SinglePred was the entry block of the function.
1419 // If so, we will need to move BB back to the entry position.
1420 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1421 MergeBasicBlockIntoOnlyPred(BB, nullptr);
1423 if (isEntry && BB != &BB->getParent()->getEntryBlock())
1424 BB->moveBefore(&BB->getParent()->getEntryBlock());
1426 // We have erased a block. Update the iterator.
1427 I = BB->getIterator();
1433 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
1434 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
1435 /// edges in ways that are non-optimal for isel. Start by eliminating these
1436 /// blocks so we can split them the way we want them.
1437 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
1438 bool MadeChange = false;
1439 // Note that this intentionally skips the entry block.
1440 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1441 BasicBlock *BB = &*I++;
1442 // If this block doesn't end with an uncond branch, ignore it.
1443 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
1444 if (!BI || !BI->isUnconditional())
1447 // If the instruction before the branch (skipping debug info) isn't a phi
1448 // node, then other stuff is happening here.
1449 BasicBlock::iterator BBI = BI->getIterator();
1450 if (BBI != BB->begin()) {
1452 while (isa<DbgInfoIntrinsic>(BBI)) {
1453 if (BBI == BB->begin())
1457 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
1461 // Do not break infinite loops.
1462 BasicBlock *DestBB = BI->getSuccessor(0);
1466 if (!canMergeBlocks(BB, DestBB))
1469 eliminateMostlyEmptyBlock(BB);
1475 /// Return true if we can merge BB into DestBB if there is a single
1476 /// unconditional branch between them, and BB contains no other non-phi
1478 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1479 const BasicBlock *DestBB) const {
1480 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1481 // the successor. If there are more complex condition (e.g. preheaders),
1482 // don't mess around with them.
1483 BasicBlock::const_iterator BBI = BB->begin();
1484 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1485 for (const User *U : PN->users()) {
1486 const Instruction *UI = cast<Instruction>(U);
1487 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1489 // IfUser is inside DestBB block and it is a PHINode then check
1490 // incoming value. If incoming value is not from BB then this is
1491 // a complex condition (e.g. preheaders) we want to avoid here.
1492 if (UI->getParent() == DestBB) {
1493 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1494 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1495 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1496 if (Insn && Insn->getParent() == BB &&
1497 Insn->getParent() != UPN->getIncomingBlock(I))
1504 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1505 // and DestBB may have conflicting incoming values for the block. If so, we
1506 // can't merge the block.
1507 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1508 if (!DestBBPN) return true; // no conflict.
1510 // Collect the preds of BB.
1511 SmallPtrSet<const BasicBlock*, 16> BBPreds;
1512 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1513 // It is faster to get preds from a PHI than with pred_iterator.
1514 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1515 BBPreds.insert(BBPN->getIncomingBlock(i));
1517 BBPreds.insert(pred_begin(BB), pred_end(BB));
1520 // Walk the preds of DestBB.
1521 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1522 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1523 if (BBPreds.count(Pred)) { // Common predecessor?
1524 BBI = DestBB->begin();
1525 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1526 const Value *V1 = PN->getIncomingValueForBlock(Pred);
1527 const Value *V2 = PN->getIncomingValueForBlock(BB);
1529 // If V2 is a phi node in BB, look up what the mapped value will be.
1530 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1531 if (V2PN->getParent() == BB)
1532 V2 = V2PN->getIncomingValueForBlock(Pred);
1534 // If there is a conflict, bail out.
1535 if (V1 != V2) return false;
1544 /// Eliminate a basic block that has only phi's and an unconditional branch in
1546 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1547 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1548 BasicBlock *DestBB = BI->getSuccessor(0);
1550 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
1552 // If the destination block has a single pred, then this is a trivial edge,
1553 // just collapse it.
1554 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1555 if (SinglePred != DestBB) {
1556 // Remember if SinglePred was the entry block of the function. If so, we
1557 // will need to move BB back to the entry position.
1558 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1559 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
1561 if (isEntry && BB != &BB->getParent()->getEntryBlock())
1562 BB->moveBefore(&BB->getParent()->getEntryBlock());
1564 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1569 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1570 // to handle the new incoming edges it is about to have.
1572 for (BasicBlock::iterator BBI = DestBB->begin();
1573 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1574 // Remove the incoming value for BB, and remember it.
1575 Value *InVal = PN->removeIncomingValue(BB, false);
1577 // Two options: either the InVal is a phi node defined in BB or it is some
1578 // value that dominates BB.
1579 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1580 if (InValPhi && InValPhi->getParent() == BB) {
1581 // Add all of the input values of the input PHI as inputs of this phi.
1582 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1583 PN->addIncoming(InValPhi->getIncomingValue(i),
1584 InValPhi->getIncomingBlock(i));
1586 // Otherwise, add one instance of the dominating value for each edge that
1587 // we will be adding.
1588 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1589 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1590 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
1592 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1593 PN->addIncoming(InVal, *PI);
1598 // The PHIs are now updated, change everything that refers to BB to use
1599 // DestBB and remove BB.
1600 BB->replaceAllUsesWith(DestBB);
1601 BB->eraseFromParent();
1604 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1607 // Computes a map of base pointer relocation instructions to corresponding
1608 // derived pointer relocation instructions given a vector of all relocate calls
1609 static void computeBaseDerivedRelocateMap(
1610 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1611 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1613 // Collect information in two maps: one primarily for locating the base object
1614 // while filling the second map; the second map is the final structure holding
1615 // a mapping between Base and corresponding Derived relocate calls
1616 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1617 for (auto *ThisRelocate : AllRelocateCalls) {
1618 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1619 ThisRelocate->getDerivedPtrIndex());
1620 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1622 for (auto &Item : RelocateIdxMap) {
1623 std::pair<unsigned, unsigned> Key = Item.first;
1624 if (Key.first == Key.second)
1625 // Base relocation: nothing to insert
1628 GCRelocateInst *I = Item.second;
1629 auto BaseKey = std::make_pair(Key.first, Key.first);
1631 // We're iterating over RelocateIdxMap so we cannot modify it.
1632 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1633 if (MaybeBase == RelocateIdxMap.end())
1634 // TODO: We might want to insert a new base object relocate and gep off
1635 // that, if there are enough derived object relocates.
1638 RelocateInstMap[MaybeBase->second].push_back(I);
1642 // Accepts a GEP and extracts the operands into a vector provided they're all
1643 // small integer constants
1644 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1645 SmallVectorImpl<Value *> &OffsetV) {
1646 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1647 // Only accept small constant integer operands
1648 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1649 if (!Op || Op->getZExtValue() > 20)
1653 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1654 OffsetV.push_back(GEP->getOperand(i));
1658 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1659 // replace, computes a replacement, and affects it.
1661 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1662 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1663 bool MadeChange = false;
1664 for (GCRelocateInst *ToReplace : Targets) {
1665 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1666 "Not relocating a derived object of the original base object");
1667 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1668 // A duplicate relocate call. TODO: coalesce duplicates.
1672 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1673 // Base and derived relocates are in different basic blocks.
1674 // In this case transform is only valid when base dominates derived
1675 // relocate. However it would be too expensive to check dominance
1676 // for each such relocate, so we skip the whole transformation.
1680 Value *Base = ToReplace->getBasePtr();
1681 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1682 if (!Derived || Derived->getPointerOperand() != Base)
1685 SmallVector<Value *, 2> OffsetV;
1686 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1689 // Create a Builder and replace the target callsite with a gep
1690 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
1692 // Insert after RelocatedBase
1693 IRBuilder<> Builder(RelocatedBase->getNextNode());
1694 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1696 // If gc_relocate does not match the actual type, cast it to the right type.
1697 // In theory, there must be a bitcast after gc_relocate if the type does not
1698 // match, and we should reuse it to get the derived pointer. But it could be
1702 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1707 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1711 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1712 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1714 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1715 // no matter there is already one or not. In this way, we can handle all cases, and
1716 // the extra bitcast should be optimized away in later passes.
1717 Value *ActualRelocatedBase = RelocatedBase;
1718 if (RelocatedBase->getType() != Base->getType()) {
1719 ActualRelocatedBase =
1720 Builder.CreateBitCast(RelocatedBase, Base->getType());
1722 Value *Replacement = Builder.CreateGEP(
1723 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1724 Replacement->takeName(ToReplace);
1725 // If the newly generated derived pointer's type does not match the original derived
1726 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
1727 Value *ActualReplacement = Replacement;
1728 if (Replacement->getType() != ToReplace->getType()) {
1730 Builder.CreateBitCast(Replacement, ToReplace->getType());
1732 ToReplace->replaceAllUsesWith(ActualReplacement);
1733 ToReplace->eraseFromParent();
1743 // %ptr = gep %base + 15
1744 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1745 // %base' = relocate(%tok, i32 4, i32 4)
1746 // %ptr' = relocate(%tok, i32 4, i32 5)
1747 // %val = load %ptr'
1752 // %ptr = gep %base + 15
1753 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1754 // %base' = gc.relocate(%tok, i32 4, i32 4)
1755 // %ptr' = gep %base' + 15
1756 // %val = load %ptr'
1757 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1758 bool MadeChange = false;
1759 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1761 for (auto *U : I.users())
1762 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1763 // Collect all the relocate calls associated with a statepoint
1764 AllRelocateCalls.push_back(Relocate);
1766 // We need atleast one base pointer relocation + one derived pointer
1767 // relocation to mangle
1768 if (AllRelocateCalls.size() < 2)
1771 // RelocateInstMap is a mapping from the base relocate instruction to the
1772 // corresponding derived relocate instructions
1773 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1774 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1775 if (RelocateInstMap.empty())
1778 for (auto &Item : RelocateInstMap)
1779 // Item.first is the RelocatedBase to offset against
1780 // Item.second is the vector of Targets to replace
1781 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1785 /// SinkCast - Sink the specified cast instruction into its user blocks
1786 static bool SinkCast(CastInst *CI) {
1787 BasicBlock *DefBB = CI->getParent();
1789 /// InsertedCasts - Only insert a cast in each block once.
1790 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1792 bool MadeChange = false;
1793 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1795 Use &TheUse = UI.getUse();
1796 Instruction *User = cast<Instruction>(*UI);
1798 // Figure out which BB this cast is used in. For PHI's this is the
1799 // appropriate predecessor block.
1800 BasicBlock *UserBB = User->getParent();
1801 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1802 UserBB = PN->getIncomingBlock(TheUse);
1805 // Preincrement use iterator so we don't invalidate it.
1808 // If the block selected to receive the cast is an EH pad that does not
1809 // allow non-PHI instructions before the terminator, we can't sink the
1811 if (UserBB->getTerminator()->isEHPad())
1814 // If this user is in the same block as the cast, don't change the cast.
1815 if (UserBB == DefBB) continue;
1817 // If we have already inserted a cast into this block, use it.
1818 CastInst *&InsertedCast = InsertedCasts[UserBB];
1820 if (!InsertedCast) {
1821 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1822 assert(InsertPt != UserBB->end());
1823 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1824 CI->getType(), "", &*InsertPt);
1827 // Replace a use of the cast with a use of the new cast.
1828 TheUse = InsertedCast;
1833 // If we removed all uses, nuke the cast.
1834 if (CI->use_empty()) {
1835 CI->eraseFromParent();
1842 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1843 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1844 /// reduce the number of virtual registers that must be created and coalesced.
1846 /// Return true if any changes are made.
1848 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1849 const DataLayout &DL) {
1850 // If this is a noop copy,
1851 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1852 EVT DstVT = TLI.getValueType(DL, CI->getType());
1854 // This is an fp<->int conversion?
1855 if (SrcVT.isInteger() != DstVT.isInteger())
1858 // If this is an extension, it will be a zero or sign extension, which
1860 if (SrcVT.bitsLT(DstVT)) return false;
1862 // If these values will be promoted, find out what they will be promoted
1863 // to. This helps us consider truncates on PPC as noop copies when they
1865 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1866 TargetLowering::TypePromoteInteger)
1867 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1868 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1869 TargetLowering::TypePromoteInteger)
1870 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1872 // If, after promotion, these are the same types, this is a noop copy.
1876 return SinkCast(CI);
1879 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1882 /// Return true if any changes were made.
1883 static bool CombineUAddWithOverflow(CmpInst *CI) {
1887 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1890 Type *Ty = AddI->getType();
1891 if (!isa<IntegerType>(Ty))
1894 // We don't want to move around uses of condition values this late, so we we
1895 // check if it is legal to create the call to the intrinsic in the basic
1896 // block containing the icmp:
1898 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1902 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1904 if (AddI->hasOneUse())
1905 assert(*AddI->user_begin() == CI && "expected!");
1908 Module *M = CI->getModule();
1909 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1911 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1913 auto *UAddWithOverflow =
1914 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1915 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1917 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1919 CI->replaceAllUsesWith(Overflow);
1920 AddI->replaceAllUsesWith(UAdd);
1921 CI->eraseFromParent();
1922 AddI->eraseFromParent();
1926 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1927 /// registers that must be created and coalesced. This is a clear win except on
1928 /// targets with multiple condition code registers (PowerPC), where it might
1929 /// lose; some adjustment may be wanted there.
1931 /// Return true if any changes are made.
1932 static bool SinkCmpExpression(CmpInst *CI) {
1933 BasicBlock *DefBB = CI->getParent();
1935 /// Only insert a cmp in each block once.
1936 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1938 bool MadeChange = false;
1939 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1941 Use &TheUse = UI.getUse();
1942 Instruction *User = cast<Instruction>(*UI);
1944 // Preincrement use iterator so we don't invalidate it.
1947 // Don't bother for PHI nodes.
1948 if (isa<PHINode>(User))
1951 // Figure out which BB this cmp is used in.
1952 BasicBlock *UserBB = User->getParent();
1954 // If this user is in the same block as the cmp, don't change the cmp.
1955 if (UserBB == DefBB) continue;
1957 // If we have already inserted a cmp into this block, use it.
1958 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1961 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1962 assert(InsertPt != UserBB->end());
1964 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1965 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1968 // Replace a use of the cmp with a use of the new cmp.
1969 TheUse = InsertedCmp;
1974 // If we removed all uses, nuke the cmp.
1975 if (CI->use_empty()) {
1976 CI->eraseFromParent();
1983 static bool OptimizeCmpExpression(CmpInst *CI) {
1984 if (SinkCmpExpression(CI))
1987 if (CombineUAddWithOverflow(CI))
1993 /// Check if the candidates could be combined with a shift instruction, which
1995 /// 1. Truncate instruction
1996 /// 2. And instruction and the imm is a mask of the low bits:
1997 /// imm & (imm+1) == 0
1998 static bool isExtractBitsCandidateUse(Instruction *User) {
1999 if (!isa<TruncInst>(User)) {
2000 if (User->getOpcode() != Instruction::And ||
2001 !isa<ConstantInt>(User->getOperand(1)))
2004 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2006 if ((Cimm & (Cimm + 1)).getBoolValue())
2012 /// Sink both shift and truncate instruction to the use of truncate's BB.
2014 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
2015 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
2016 const TargetLowering &TLI, const DataLayout &DL) {
2017 BasicBlock *UserBB = User->getParent();
2018 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
2019 TruncInst *TruncI = dyn_cast<TruncInst>(User);
2020 bool MadeChange = false;
2022 for (Value::user_iterator TruncUI = TruncI->user_begin(),
2023 TruncE = TruncI->user_end();
2024 TruncUI != TruncE;) {
2026 Use &TruncTheUse = TruncUI.getUse();
2027 Instruction *TruncUser = cast<Instruction>(*TruncUI);
2028 // Preincrement use iterator so we don't invalidate it.
2032 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2036 // If the use is actually a legal node, there will not be an
2037 // implicit truncate.
2038 // FIXME: always querying the result type is just an
2039 // approximation; some nodes' legality is determined by the
2040 // operand or other means. There's no good way to find out though.
2041 if (TLI.isOperationLegalOrCustom(
2042 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2045 // Don't bother for PHI nodes.
2046 if (isa<PHINode>(TruncUser))
2049 BasicBlock *TruncUserBB = TruncUser->getParent();
2051 if (UserBB == TruncUserBB)
2054 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2055 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2057 if (!InsertedShift && !InsertedTrunc) {
2058 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2059 assert(InsertPt != TruncUserBB->end());
2061 if (ShiftI->getOpcode() == Instruction::AShr)
2062 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2065 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2069 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2071 assert(TruncInsertPt != TruncUserBB->end());
2073 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2074 TruncI->getType(), "", &*TruncInsertPt);
2078 TruncTheUse = InsertedTrunc;
2084 /// Sink the shift *right* instruction into user blocks if the uses could
2085 /// potentially be combined with this shift instruction and generate BitExtract
2086 /// instruction. It will only be applied if the architecture supports BitExtract
2087 /// instruction. Here is an example:
2089 /// %x.extract.shift = lshr i64 %arg1, 32
2091 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2095 /// %x.extract.shift.1 = lshr i64 %arg1, 32
2096 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2098 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
2100 /// Return true if any changes are made.
2101 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
2102 const TargetLowering &TLI,
2103 const DataLayout &DL) {
2104 BasicBlock *DefBB = ShiftI->getParent();
2106 /// Only insert instructions in each block once.
2107 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
2109 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2111 bool MadeChange = false;
2112 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2114 Use &TheUse = UI.getUse();
2115 Instruction *User = cast<Instruction>(*UI);
2116 // Preincrement use iterator so we don't invalidate it.
2119 // Don't bother for PHI nodes.
2120 if (isa<PHINode>(User))
2123 if (!isExtractBitsCandidateUse(User))
2126 BasicBlock *UserBB = User->getParent();
2128 if (UserBB == DefBB) {
2129 // If the shift and truncate instruction are in the same BB. The use of
2130 // the truncate(TruncUse) may still introduce another truncate if not
2131 // legal. In this case, we would like to sink both shift and truncate
2132 // instruction to the BB of TruncUse.
2135 // i64 shift.result = lshr i64 opnd, imm
2136 // trunc.result = trunc shift.result to i16
2139 // ----> We will have an implicit truncate here if the architecture does
2140 // not have i16 compare.
2141 // cmp i16 trunc.result, opnd2
2143 if (isa<TruncInst>(User) && shiftIsLegal
2144 // If the type of the truncate is legal, no trucate will be
2145 // introduced in other basic blocks.
2147 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2149 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2153 // If we have already inserted a shift into this block, use it.
2154 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2156 if (!InsertedShift) {
2157 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2158 assert(InsertPt != UserBB->end());
2160 if (ShiftI->getOpcode() == Instruction::AShr)
2161 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2164 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2170 // Replace a use of the shift with a use of the new shift.
2171 TheUse = InsertedShift;
2174 // If we removed all uses, nuke the shift.
2175 if (ShiftI->use_empty())
2176 ShiftI->eraseFromParent();
2181 // Translate a masked load intrinsic like
2182 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
2183 // <16 x i1> %mask, <16 x i32> %passthru)
2184 // to a chain of basic blocks, with loading element one-by-one if
2185 // the appropriate mask bit is set
2187 // %1 = bitcast i8* %addr to i32*
2188 // %2 = extractelement <16 x i1> %mask, i32 0
2189 // %3 = icmp eq i1 %2, true
2190 // br i1 %3, label %cond.load, label %else
2192 //cond.load: ; preds = %0
2193 // %4 = getelementptr i32* %1, i32 0
2194 // %5 = load i32* %4
2195 // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
2198 //else: ; preds = %0, %cond.load
2199 // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
2200 // %7 = extractelement <16 x i1> %mask, i32 1
2201 // %8 = icmp eq i1 %7, true
2202 // br i1 %8, label %cond.load1, label %else2
2204 //cond.load1: ; preds = %else
2205 // %9 = getelementptr i32* %1, i32 1
2206 // %10 = load i32* %9
2207 // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
2210 //else2: ; preds = %else, %cond.load1
2211 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2212 // %12 = extractelement <16 x i1> %mask, i32 2
2213 // %13 = icmp eq i1 %12, true
2214 // br i1 %13, label %cond.load4, label %else5
2216 static void ScalarizeMaskedLoad(CallInst *CI) {
2217 Value *Ptr = CI->getArgOperand(0);
2218 Value *Alignment = CI->getArgOperand(1);
2219 Value *Mask = CI->getArgOperand(2);
2220 Value *Src0 = CI->getArgOperand(3);
2222 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2223 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2224 assert(VecType && "Unexpected return type of masked load intrinsic");
2226 Type *EltTy = CI->getType()->getVectorElementType();
2228 IRBuilder<> Builder(CI->getContext());
2229 Instruction *InsertPt = CI;
2230 BasicBlock *IfBlock = CI->getParent();
2231 BasicBlock *CondBlock = nullptr;
2232 BasicBlock *PrevIfBlock = CI->getParent();
2234 Builder.SetInsertPoint(InsertPt);
2235 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2237 // Short-cut if the mask is all-true.
2238 bool IsAllOnesMask = isa<Constant>(Mask) &&
2239 cast<Constant>(Mask)->isAllOnesValue();
2241 if (IsAllOnesMask) {
2242 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
2243 CI->replaceAllUsesWith(NewI);
2244 CI->eraseFromParent();
2248 // Adjust alignment for the scalar instruction.
2249 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
2250 // Bitcast %addr fron i8* to EltTy*
2252 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2253 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2254 unsigned VectorWidth = VecType->getNumElements();
2256 Value *UndefVal = UndefValue::get(VecType);
2258 // The result vector
2259 Value *VResult = UndefVal;
2261 if (isa<ConstantVector>(Mask)) {
2262 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2263 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2266 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2267 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2268 VResult = Builder.CreateInsertElement(VResult, Load,
2269 Builder.getInt32(Idx));
2271 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2272 CI->replaceAllUsesWith(NewI);
2273 CI->eraseFromParent();
2277 PHINode *Phi = nullptr;
2278 Value *PrevPhi = UndefVal;
2280 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2282 // Fill the "else" block, created in the previous iteration
2284 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2285 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2286 // %to_load = icmp eq i1 %mask_1, true
2287 // br i1 %to_load, label %cond.load, label %else
2290 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2291 Phi->addIncoming(VResult, CondBlock);
2292 Phi->addIncoming(PrevPhi, PrevIfBlock);
2297 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2298 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2299 ConstantInt::get(Predicate->getType(), 1));
2301 // Create "cond" block
2303 // %EltAddr = getelementptr i32* %1, i32 0
2304 // %Elt = load i32* %EltAddr
2305 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2307 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
2308 Builder.SetInsertPoint(InsertPt);
2311 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2312 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2313 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
2315 // Create "else" block, fill it in the next iteration
2316 BasicBlock *NewIfBlock =
2317 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2318 Builder.SetInsertPoint(InsertPt);
2319 Instruction *OldBr = IfBlock->getTerminator();
2320 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2321 OldBr->eraseFromParent();
2322 PrevIfBlock = IfBlock;
2323 IfBlock = NewIfBlock;
2326 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2327 Phi->addIncoming(VResult, CondBlock);
2328 Phi->addIncoming(PrevPhi, PrevIfBlock);
2329 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2330 CI->replaceAllUsesWith(NewI);
2331 CI->eraseFromParent();
2334 // Translate a masked store intrinsic, like
2335 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
2337 // to a chain of basic blocks, that stores element one-by-one if
2338 // the appropriate mask bit is set
2340 // %1 = bitcast i8* %addr to i32*
2341 // %2 = extractelement <16 x i1> %mask, i32 0
2342 // %3 = icmp eq i1 %2, true
2343 // br i1 %3, label %cond.store, label %else
2345 // cond.store: ; preds = %0
2346 // %4 = extractelement <16 x i32> %val, i32 0
2347 // %5 = getelementptr i32* %1, i32 0
2348 // store i32 %4, i32* %5
2351 // else: ; preds = %0, %cond.store
2352 // %6 = extractelement <16 x i1> %mask, i32 1
2353 // %7 = icmp eq i1 %6, true
2354 // br i1 %7, label %cond.store1, label %else2
2356 // cond.store1: ; preds = %else
2357 // %8 = extractelement <16 x i32> %val, i32 1
2358 // %9 = getelementptr i32* %1, i32 1
2359 // store i32 %8, i32* %9
2362 static void ScalarizeMaskedStore(CallInst *CI) {
2363 Value *Src = CI->getArgOperand(0);
2364 Value *Ptr = CI->getArgOperand(1);
2365 Value *Alignment = CI->getArgOperand(2);
2366 Value *Mask = CI->getArgOperand(3);
2368 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2369 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
2370 assert(VecType && "Unexpected data type in masked store intrinsic");
2372 Type *EltTy = VecType->getElementType();
2374 IRBuilder<> Builder(CI->getContext());
2375 Instruction *InsertPt = CI;
2376 BasicBlock *IfBlock = CI->getParent();
2377 Builder.SetInsertPoint(InsertPt);
2378 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2380 // Short-cut if the mask is all-true.
2381 bool IsAllOnesMask = isa<Constant>(Mask) &&
2382 cast<Constant>(Mask)->isAllOnesValue();
2384 if (IsAllOnesMask) {
2385 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
2386 CI->eraseFromParent();
2390 // Adjust alignment for the scalar instruction.
2391 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
2392 // Bitcast %addr fron i8* to EltTy*
2394 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2395 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2396 unsigned VectorWidth = VecType->getNumElements();
2398 if (isa<ConstantVector>(Mask)) {
2399 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2400 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2402 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2404 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2405 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2407 CI->eraseFromParent();
2411 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2413 // Fill the "else" block, created in the previous iteration
2415 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2416 // %to_store = icmp eq i1 %mask_1, true
2417 // br i1 %to_store, label %cond.store, label %else
2419 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2420 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2421 ConstantInt::get(Predicate->getType(), 1));
2423 // Create "cond" block
2425 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
2426 // %EltAddr = getelementptr i32* %1, i32 0
2427 // %store i32 %OneElt, i32* %EltAddr
2429 BasicBlock *CondBlock =
2430 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
2431 Builder.SetInsertPoint(InsertPt);
2433 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2435 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2436 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2438 // Create "else" block, fill it in the next iteration
2439 BasicBlock *NewIfBlock =
2440 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2441 Builder.SetInsertPoint(InsertPt);
2442 Instruction *OldBr = IfBlock->getTerminator();
2443 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2444 OldBr->eraseFromParent();
2445 IfBlock = NewIfBlock;
2447 CI->eraseFromParent();
2450 // Translate a masked gather intrinsic like
2451 // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
2452 // <16 x i1> %Mask, <16 x i32> %Src)
2453 // to a chain of basic blocks, with loading element one-by-one if
2454 // the appropriate mask bit is set
2456 // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
2457 // % Mask0 = extractelement <16 x i1> %Mask, i32 0
2458 // % ToLoad0 = icmp eq i1 % Mask0, true
2459 // br i1 % ToLoad0, label %cond.load, label %else
2462 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2463 // % Load0 = load i32, i32* % Ptr0, align 4
2464 // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
2468 // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
2469 // % Mask1 = extractelement <16 x i1> %Mask, i32 1
2470 // % ToLoad1 = icmp eq i1 % Mask1, true
2471 // br i1 % ToLoad1, label %cond.load1, label %else2
2474 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2475 // % Load1 = load i32, i32* % Ptr1, align 4
2476 // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
2479 // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
2480 // ret <16 x i32> %Result
2481 static void ScalarizeMaskedGather(CallInst *CI) {
2482 Value *Ptrs = CI->getArgOperand(0);
2483 Value *Alignment = CI->getArgOperand(1);
2484 Value *Mask = CI->getArgOperand(2);
2485 Value *Src0 = CI->getArgOperand(3);
2487 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2489 assert(VecType && "Unexpected return type of masked load intrinsic");
2491 IRBuilder<> Builder(CI->getContext());
2492 Instruction *InsertPt = CI;
2493 BasicBlock *IfBlock = CI->getParent();
2494 BasicBlock *CondBlock = nullptr;
2495 BasicBlock *PrevIfBlock = CI->getParent();
2496 Builder.SetInsertPoint(InsertPt);
2497 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2499 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2501 Value *UndefVal = UndefValue::get(VecType);
2503 // The result vector
2504 Value *VResult = UndefVal;
2505 unsigned VectorWidth = VecType->getNumElements();
2507 // Shorten the way if the mask is a vector of constants.
2508 bool IsConstMask = isa<ConstantVector>(Mask);
2511 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2512 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2514 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2515 "Ptr" + Twine(Idx));
2516 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2517 "Load" + Twine(Idx));
2518 VResult = Builder.CreateInsertElement(VResult, Load,
2519 Builder.getInt32(Idx),
2520 "Res" + Twine(Idx));
2522 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2523 CI->replaceAllUsesWith(NewI);
2524 CI->eraseFromParent();
2528 PHINode *Phi = nullptr;
2529 Value *PrevPhi = UndefVal;
2531 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2533 // Fill the "else" block, created in the previous iteration
2535 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
2536 // %ToLoad1 = icmp eq i1 %Mask1, true
2537 // br i1 %ToLoad1, label %cond.load, label %else
2540 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2541 Phi->addIncoming(VResult, CondBlock);
2542 Phi->addIncoming(PrevPhi, PrevIfBlock);
2547 Value *Predicate = Builder.CreateExtractElement(Mask,
2548 Builder.getInt32(Idx),
2549 "Mask" + Twine(Idx));
2550 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2551 ConstantInt::get(Predicate->getType(), 1),
2552 "ToLoad" + Twine(Idx));
2554 // Create "cond" block
2556 // %EltAddr = getelementptr i32* %1, i32 0
2557 // %Elt = load i32* %EltAddr
2558 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2560 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
2561 Builder.SetInsertPoint(InsertPt);
2563 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2564 "Ptr" + Twine(Idx));
2565 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2566 "Load" + Twine(Idx));
2567 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
2568 "Res" + Twine(Idx));
2570 // Create "else" block, fill it in the next iteration
2571 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2572 Builder.SetInsertPoint(InsertPt);
2573 Instruction *OldBr = IfBlock->getTerminator();
2574 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2575 OldBr->eraseFromParent();
2576 PrevIfBlock = IfBlock;
2577 IfBlock = NewIfBlock;
2580 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2581 Phi->addIncoming(VResult, CondBlock);
2582 Phi->addIncoming(PrevPhi, PrevIfBlock);
2583 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2584 CI->replaceAllUsesWith(NewI);
2585 CI->eraseFromParent();
2588 // Translate a masked scatter intrinsic, like
2589 // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
2591 // to a chain of basic blocks, that stores element one-by-one if
2592 // the appropriate mask bit is set.
2594 // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
2595 // % Mask0 = extractelement <16 x i1> % Mask, i32 0
2596 // % ToStore0 = icmp eq i1 % Mask0, true
2597 // br i1 %ToStore0, label %cond.store, label %else
2600 // % Elt0 = extractelement <16 x i32> %Src, i32 0
2601 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2602 // store i32 %Elt0, i32* % Ptr0, align 4
2606 // % Mask1 = extractelement <16 x i1> % Mask, i32 1
2607 // % ToStore1 = icmp eq i1 % Mask1, true
2608 // br i1 % ToStore1, label %cond.store1, label %else2
2611 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2612 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2613 // store i32 % Elt1, i32* % Ptr1, align 4
2616 static void ScalarizeMaskedScatter(CallInst *CI) {
2617 Value *Src = CI->getArgOperand(0);
2618 Value *Ptrs = CI->getArgOperand(1);
2619 Value *Alignment = CI->getArgOperand(2);
2620 Value *Mask = CI->getArgOperand(3);
2622 assert(isa<VectorType>(Src->getType()) &&
2623 "Unexpected data type in masked scatter intrinsic");
2624 assert(isa<VectorType>(Ptrs->getType()) &&
2625 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
2626 "Vector of pointers is expected in masked scatter intrinsic");
2628 IRBuilder<> Builder(CI->getContext());
2629 Instruction *InsertPt = CI;
2630 BasicBlock *IfBlock = CI->getParent();
2631 Builder.SetInsertPoint(InsertPt);
2632 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2634 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2635 unsigned VectorWidth = Src->getType()->getVectorNumElements();
2637 // Shorten the way if the mask is a vector of constants.
2638 bool IsConstMask = isa<ConstantVector>(Mask);
2641 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2642 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2644 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2645 "Elt" + Twine(Idx));
2646 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2647 "Ptr" + Twine(Idx));
2648 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2650 CI->eraseFromParent();
2653 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2654 // Fill the "else" block, created in the previous iteration
2656 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
2657 // % ToStore = icmp eq i1 % Mask1, true
2658 // br i1 % ToStore, label %cond.store, label %else
2660 Value *Predicate = Builder.CreateExtractElement(Mask,
2661 Builder.getInt32(Idx),
2662 "Mask" + Twine(Idx));
2664 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2665 ConstantInt::get(Predicate->getType(), 1),
2666 "ToStore" + Twine(Idx));
2668 // Create "cond" block
2670 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2671 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2672 // %store i32 % Elt1, i32* % Ptr1
2674 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2675 Builder.SetInsertPoint(InsertPt);
2677 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2678 "Elt" + Twine(Idx));
2679 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2680 "Ptr" + Twine(Idx));
2681 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2683 // Create "else" block, fill it in the next iteration
2684 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2685 Builder.SetInsertPoint(InsertPt);
2686 Instruction *OldBr = IfBlock->getTerminator();
2687 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2688 OldBr->eraseFromParent();
2689 IfBlock = NewIfBlock;
2691 CI->eraseFromParent();
2694 /// If counting leading or trailing zeros is an expensive operation and a zero
2695 /// input is defined, add a check for zero to avoid calling the intrinsic.
2697 /// We want to transform:
2698 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2702 /// %cmpz = icmp eq i64 %A, 0
2703 /// br i1 %cmpz, label %cond.end, label %cond.false
2705 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2706 /// br label %cond.end
2708 /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2710 /// If the transform is performed, return true and set ModifiedDT to true.
2711 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2712 const TargetLowering *TLI,
2713 const DataLayout *DL,
2718 // If a zero input is undefined, it doesn't make sense to despeculate that.
2719 if (match(CountZeros->getOperand(1), m_One()))
2722 // If it's cheap to speculate, there's nothing to do.
2723 auto IntrinsicID = CountZeros->getIntrinsicID();
2724 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2725 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2728 // Only handle legal scalar cases. Anything else requires too much work.
2729 Type *Ty = CountZeros->getType();
2730 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
2731 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
2734 // The intrinsic will be sunk behind a compare against zero and branch.
2735 BasicBlock *StartBlock = CountZeros->getParent();
2736 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2738 // Create another block after the count zero intrinsic. A PHI will be added
2739 // in this block to select the result of the intrinsic or the bit-width
2740 // constant if the input to the intrinsic is zero.
2741 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2742 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2744 // Set up a builder to create a compare, conditional branch, and PHI.
2745 IRBuilder<> Builder(CountZeros->getContext());
2746 Builder.SetInsertPoint(StartBlock->getTerminator());
2747 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2749 // Replace the unconditional branch that was created by the first split with
2750 // a compare against zero and a conditional branch.
2751 Value *Zero = Constant::getNullValue(Ty);
2752 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2753 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2754 StartBlock->getTerminator()->eraseFromParent();
2756 // Create a PHI in the end block to select either the output of the intrinsic
2757 // or the bit width of the operand.
2758 Builder.SetInsertPoint(&EndBlock->front());
2759 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2760 CountZeros->replaceAllUsesWith(PN);
2761 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2762 PN->addIncoming(BitWidth, StartBlock);
2763 PN->addIncoming(CountZeros, CallBlock);
2765 // We are explicitly handling the zero case, so we can set the intrinsic's
2766 // undefined zero argument to 'true'. This will also prevent reprocessing the
2767 // intrinsic; we only despeculate when a zero input is defined.
2768 CountZeros->setArgOperand(1, Builder.getTrue());
2773 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
2774 BasicBlock *BB = CI->getParent();
2776 // Lower inline assembly if we can.
2777 // If we found an inline asm expession, and if the target knows how to
2778 // lower it to normal LLVM code, do so now.
2779 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2780 if (TLI->ExpandInlineAsm(CI)) {
2781 // Avoid invalidating the iterator.
2782 CurInstIterator = BB->begin();
2783 // Avoid processing instructions out of order, which could cause
2784 // reuse before a value is defined.
2788 // Sink address computing for memory operands into the block.
2789 if (optimizeInlineAsmInst(CI))
2793 // Align the pointer arguments to this call if the target thinks it's a good
2795 unsigned MinSize, PrefAlign;
2796 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2797 for (auto &Arg : CI->arg_operands()) {
2798 // We want to align both objects whose address is used directly and
2799 // objects whose address is used in casts and GEPs, though it only makes
2800 // sense for GEPs if the offset is a multiple of the desired alignment and
2801 // if size - offset meets the size threshold.
2802 if (!Arg->getType()->isPointerTy())
2804 APInt Offset(DL->getPointerSizeInBits(
2805 cast<PointerType>(Arg->getType())->getAddressSpace()),
2807 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2808 uint64_t Offset2 = Offset.getLimitedValue();
2809 if ((Offset2 & (PrefAlign-1)) != 0)
2812 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2813 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2814 AI->setAlignment(PrefAlign);
2815 // Global variables can only be aligned if they are defined in this
2816 // object (i.e. they are uniquely initialized in this object), and
2817 // over-aligning global variables that have an explicit section is
2820 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2821 GV->getAlignment() < PrefAlign &&
2822 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
2824 GV->setAlignment(PrefAlign);
2826 // If this is a memcpy (or similar) then we may be able to improve the
2828 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2829 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2830 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2831 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2832 if (Align > MI->getAlignment())
2833 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2837 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2839 switch (II->getIntrinsicID()) {
2841 case Intrinsic::objectsize: {
2842 // Lower all uses of llvm.objectsize.*
2843 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
2844 Type *ReturnTy = CI->getType();
2845 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
2847 // Substituting this can cause recursive simplifications, which can
2848 // invalidate our iterator. Use a WeakVH to hold onto it in case this
2850 WeakVH IterHandle(&*CurInstIterator);
2852 replaceAndRecursivelySimplify(CI, RetVal,
2855 // If the iterator instruction was recursively deleted, start over at the
2856 // start of the block.
2857 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
2858 CurInstIterator = BB->begin();
2863 case Intrinsic::masked_load: {
2864 // Scalarize unsupported vector masked load
2865 if (!TTI->isLegalMaskedLoad(CI->getType())) {
2866 ScalarizeMaskedLoad(CI);
2872 case Intrinsic::masked_store: {
2873 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
2874 ScalarizeMaskedStore(CI);
2880 case Intrinsic::masked_gather: {
2881 if (!TTI->isLegalMaskedGather(CI->getType())) {
2882 ScalarizeMaskedGather(CI);
2888 case Intrinsic::masked_scatter: {
2889 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
2890 ScalarizeMaskedScatter(CI);
2896 case Intrinsic::aarch64_stlxr:
2897 case Intrinsic::aarch64_stxr: {
2898 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2899 if (!ExtVal || !ExtVal->hasOneUse() ||
2900 ExtVal->getParent() == CI->getParent())
2902 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2903 ExtVal->moveBefore(CI);
2904 // Mark this instruction as "inserted by CGP", so that other
2905 // optimizations don't touch it.
2906 InsertedInsts.insert(ExtVal);
2909 case Intrinsic::invariant_group_barrier:
2910 II->replaceAllUsesWith(II->getArgOperand(0));
2911 II->eraseFromParent();
2914 case Intrinsic::cttz:
2915 case Intrinsic::ctlz:
2916 // If counting zeros is expensive, try to avoid it.
2917 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2921 // Unknown address space.
2922 // TODO: Target hook to pick which address space the intrinsic cares
2924 unsigned AddrSpace = ~0u;
2925 SmallVector<Value*, 2> PtrOps;
2927 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
2928 while (!PtrOps.empty())
2929 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
2934 // From here on out we're working with named functions.
2935 if (!CI->getCalledFunction()) return false;
2937 // Lower all default uses of _chk calls. This is very similar
2938 // to what InstCombineCalls does, but here we are only lowering calls
2939 // to fortified library functions (e.g. __memcpy_chk) that have the default
2940 // "don't know" as the objectsize. Anything else should be left alone.
2941 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2942 if (Value *V = Simplifier.optimizeCall(CI)) {
2943 CI->replaceAllUsesWith(V);
2944 CI->eraseFromParent();
2950 /// Look for opportunities to duplicate return instructions to the predecessor
2951 /// to enable tail call optimizations. The case it is currently looking for is:
2954 /// %tmp0 = tail call i32 @f0()
2955 /// br label %return
2957 /// %tmp1 = tail call i32 @f1()
2958 /// br label %return
2960 /// %tmp2 = tail call i32 @f2()
2961 /// br label %return
2963 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2971 /// %tmp0 = tail call i32 @f0()
2974 /// %tmp1 = tail call i32 @f1()
2977 /// %tmp2 = tail call i32 @f2()
2980 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
2984 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
2988 PHINode *PN = nullptr;
2989 BitCastInst *BCI = nullptr;
2990 Value *V = RI->getReturnValue();
2992 BCI = dyn_cast<BitCastInst>(V);
2994 V = BCI->getOperand(0);
2996 PN = dyn_cast<PHINode>(V);
3001 if (PN && PN->getParent() != BB)
3004 // It's not safe to eliminate the sign / zero extension of the return value.
3005 // See llvm::isInTailCallPosition().
3006 const Function *F = BB->getParent();
3007 AttributeSet CallerAttrs = F->getAttributes();
3008 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
3009 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
3012 // Make sure there are no instructions between the PHI and return, or that the
3013 // return is the first instruction in the block.
3015 BasicBlock::iterator BI = BB->begin();
3016 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
3018 // Also skip over the bitcast.
3023 BasicBlock::iterator BI = BB->begin();
3024 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
3029 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
3031 SmallVector<CallInst*, 4> TailCalls;
3033 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
3034 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
3035 // Make sure the phi value is indeed produced by the tail call.
3036 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
3037 TLI->mayBeEmittedAsTailCall(CI))
3038 TailCalls.push_back(CI);
3041 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
3042 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
3043 if (!VisitedBBs.insert(*PI).second)
3046 BasicBlock::InstListType &InstList = (*PI)->getInstList();
3047 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
3048 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
3049 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
3053 CallInst *CI = dyn_cast<CallInst>(&*RI);
3054 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
3055 TailCalls.push_back(CI);
3059 bool Changed = false;
3060 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
3061 CallInst *CI = TailCalls[i];
3064 // Conservatively require the attributes of the call to match those of the
3065 // return. Ignore noalias because it doesn't affect the call sequence.
3066 AttributeSet CalleeAttrs = CS.getAttributes();
3067 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
3068 removeAttribute(Attribute::NoAlias) !=
3069 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
3070 removeAttribute(Attribute::NoAlias))
3073 // Make sure the call instruction is followed by an unconditional branch to
3074 // the return block.
3075 BasicBlock *CallBB = CI->getParent();
3076 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
3077 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
3080 // Duplicate the return into CallBB.
3081 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
3082 ModifiedDT = Changed = true;
3086 // If we eliminated all predecessors of the block, delete the block now.
3087 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
3088 BB->eraseFromParent();
3093 //===----------------------------------------------------------------------===//
3094 // Memory Optimization
3095 //===----------------------------------------------------------------------===//
3099 /// This is an extended version of TargetLowering::AddrMode
3100 /// which holds actual Value*'s for register values.
3101 struct ExtAddrMode : public TargetLowering::AddrMode {
3104 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
3105 void print(raw_ostream &OS) const;
3108 bool operator==(const ExtAddrMode& O) const {
3109 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
3110 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
3111 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
3116 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3122 void ExtAddrMode::print(raw_ostream &OS) const {
3123 bool NeedPlus = false;
3126 OS << (NeedPlus ? " + " : "")
3128 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3133 OS << (NeedPlus ? " + " : "")
3139 OS << (NeedPlus ? " + " : "")
3141 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3145 OS << (NeedPlus ? " + " : "")
3147 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3153 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3154 void ExtAddrMode::dump() const {
3160 /// \brief This class provides transaction based operation on the IR.
3161 /// Every change made through this class is recorded in the internal state and
3162 /// can be undone (rollback) until commit is called.
3163 class TypePromotionTransaction {
3165 /// \brief This represents the common interface of the individual transaction.
3166 /// Each class implements the logic for doing one specific modification on
3167 /// the IR via the TypePromotionTransaction.
3168 class TypePromotionAction {
3170 /// The Instruction modified.
3174 /// \brief Constructor of the action.
3175 /// The constructor performs the related action on the IR.
3176 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3178 virtual ~TypePromotionAction() {}
3180 /// \brief Undo the modification done by this action.
3181 /// When this method is called, the IR must be in the same state as it was
3182 /// before this action was applied.
3183 /// \pre Undoing the action works if and only if the IR is in the exact same
3184 /// state as it was directly after this action was applied.
3185 virtual void undo() = 0;
3187 /// \brief Advocate every change made by this action.
3188 /// When the results on the IR of the action are to be kept, it is important
3189 /// to call this function, otherwise hidden information may be kept forever.
3190 virtual void commit() {
3191 // Nothing to be done, this action is not doing anything.
3195 /// \brief Utility to remember the position of an instruction.
3196 class InsertionHandler {
3197 /// Position of an instruction.
3198 /// Either an instruction:
3199 /// - Is the first in a basic block: BB is used.
3200 /// - Has a previous instructon: PrevInst is used.
3202 Instruction *PrevInst;
3205 /// Remember whether or not the instruction had a previous instruction.
3206 bool HasPrevInstruction;
3209 /// \brief Record the position of \p Inst.
3210 InsertionHandler(Instruction *Inst) {
3211 BasicBlock::iterator It = Inst->getIterator();
3212 HasPrevInstruction = (It != (Inst->getParent()->begin()));
3213 if (HasPrevInstruction)
3214 Point.PrevInst = &*--It;
3216 Point.BB = Inst->getParent();
3219 /// \brief Insert \p Inst at the recorded position.
3220 void insert(Instruction *Inst) {
3221 if (HasPrevInstruction) {
3222 if (Inst->getParent())
3223 Inst->removeFromParent();
3224 Inst->insertAfter(Point.PrevInst);
3226 Instruction *Position = &*Point.BB->getFirstInsertionPt();
3227 if (Inst->getParent())
3228 Inst->moveBefore(Position);
3230 Inst->insertBefore(Position);
3235 /// \brief Move an instruction before another.
3236 class InstructionMoveBefore : public TypePromotionAction {
3237 /// Original position of the instruction.
3238 InsertionHandler Position;
3241 /// \brief Move \p Inst before \p Before.
3242 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
3243 : TypePromotionAction(Inst), Position(Inst) {
3244 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
3245 Inst->moveBefore(Before);
3248 /// \brief Move the instruction back to its original position.
3249 void undo() override {
3250 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3251 Position.insert(Inst);
3255 /// \brief Set the operand of an instruction with a new value.
3256 class OperandSetter : public TypePromotionAction {
3257 /// Original operand of the instruction.
3259 /// Index of the modified instruction.
3263 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
3264 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3265 : TypePromotionAction(Inst), Idx(Idx) {
3266 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3267 << "for:" << *Inst << "\n"
3268 << "with:" << *NewVal << "\n");
3269 Origin = Inst->getOperand(Idx);
3270 Inst->setOperand(Idx, NewVal);
3273 /// \brief Restore the original value of the instruction.
3274 void undo() override {
3275 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3276 << "for: " << *Inst << "\n"
3277 << "with: " << *Origin << "\n");
3278 Inst->setOperand(Idx, Origin);
3282 /// \brief Hide the operands of an instruction.
3283 /// Do as if this instruction was not using any of its operands.
3284 class OperandsHider : public TypePromotionAction {
3285 /// The list of original operands.
3286 SmallVector<Value *, 4> OriginalValues;
3289 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
3290 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3291 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3292 unsigned NumOpnds = Inst->getNumOperands();
3293 OriginalValues.reserve(NumOpnds);
3294 for (unsigned It = 0; It < NumOpnds; ++It) {
3295 // Save the current operand.
3296 Value *Val = Inst->getOperand(It);
3297 OriginalValues.push_back(Val);
3299 // We could use OperandSetter here, but that would imply an overhead
3300 // that we are not willing to pay.
3301 Inst->setOperand(It, UndefValue::get(Val->getType()));
3305 /// \brief Restore the original list of uses.
3306 void undo() override {
3307 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3308 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3309 Inst->setOperand(It, OriginalValues[It]);
3313 /// \brief Build a truncate instruction.
3314 class TruncBuilder : public TypePromotionAction {
3317 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
3319 /// trunc Opnd to Ty.
3320 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3321 IRBuilder<> Builder(Opnd);
3322 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3323 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3326 /// \brief Get the built value.
3327 Value *getBuiltValue() { return Val; }
3329 /// \brief Remove the built instruction.
3330 void undo() override {
3331 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3332 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3333 IVal->eraseFromParent();
3337 /// \brief Build a sign extension instruction.
3338 class SExtBuilder : public TypePromotionAction {
3341 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
3343 /// sext Opnd to Ty.
3344 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3345 : TypePromotionAction(InsertPt) {
3346 IRBuilder<> Builder(InsertPt);
3347 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3348 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3351 /// \brief Get the built value.
3352 Value *getBuiltValue() { return Val; }
3354 /// \brief Remove the built instruction.
3355 void undo() override {
3356 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3357 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3358 IVal->eraseFromParent();
3362 /// \brief Build a zero extension instruction.
3363 class ZExtBuilder : public TypePromotionAction {
3366 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
3368 /// zext Opnd to Ty.
3369 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3370 : TypePromotionAction(InsertPt) {
3371 IRBuilder<> Builder(InsertPt);
3372 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3373 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3376 /// \brief Get the built value.
3377 Value *getBuiltValue() { return Val; }
3379 /// \brief Remove the built instruction.
3380 void undo() override {
3381 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3382 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3383 IVal->eraseFromParent();
3387 /// \brief Mutate an instruction to another type.
3388 class TypeMutator : public TypePromotionAction {
3389 /// Record the original type.
3393 /// \brief Mutate the type of \p Inst into \p NewTy.
3394 TypeMutator(Instruction *Inst, Type *NewTy)
3395 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3396 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3398 Inst->mutateType(NewTy);
3401 /// \brief Mutate the instruction back to its original type.
3402 void undo() override {
3403 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3405 Inst->mutateType(OrigTy);
3409 /// \brief Replace the uses of an instruction by another instruction.
3410 class UsesReplacer : public TypePromotionAction {
3411 /// Helper structure to keep track of the replaced uses.
3412 struct InstructionAndIdx {
3413 /// The instruction using the instruction.
3415 /// The index where this instruction is used for Inst.
3417 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3418 : Inst(Inst), Idx(Idx) {}
3421 /// Keep track of the original uses (pair Instruction, Index).
3422 SmallVector<InstructionAndIdx, 4> OriginalUses;
3423 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
3426 /// \brief Replace all the use of \p Inst by \p New.
3427 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
3428 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3430 // Record the original uses.
3431 for (Use &U : Inst->uses()) {
3432 Instruction *UserI = cast<Instruction>(U.getUser());
3433 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3435 // Now, we can replace the uses.
3436 Inst->replaceAllUsesWith(New);
3439 /// \brief Reassign the original uses of Inst to Inst.
3440 void undo() override {
3441 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3442 for (use_iterator UseIt = OriginalUses.begin(),
3443 EndIt = OriginalUses.end();
3444 UseIt != EndIt; ++UseIt) {
3445 UseIt->Inst->setOperand(UseIt->Idx, Inst);
3450 /// \brief Remove an instruction from the IR.
3451 class InstructionRemover : public TypePromotionAction {
3452 /// Original position of the instruction.
3453 InsertionHandler Inserter;
3454 /// Helper structure to hide all the link to the instruction. In other
3455 /// words, this helps to do as if the instruction was removed.
3456 OperandsHider Hider;
3457 /// Keep track of the uses replaced, if any.
3458 UsesReplacer *Replacer;
3461 /// \brief Remove all reference of \p Inst and optinally replace all its
3463 /// \pre If !Inst->use_empty(), then New != nullptr
3464 InstructionRemover(Instruction *Inst, Value *New = nullptr)
3465 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3468 Replacer = new UsesReplacer(Inst, New);
3469 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3470 Inst->removeFromParent();
3473 ~InstructionRemover() override { delete Replacer; }
3475 /// \brief Really remove the instruction.
3476 void commit() override { delete Inst; }
3478 /// \brief Resurrect the instruction and reassign it to the proper uses if
3479 /// new value was provided when build this action.
3480 void undo() override {
3481 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3482 Inserter.insert(Inst);
3490 /// Restoration point.
3491 /// The restoration point is a pointer to an action instead of an iterator
3492 /// because the iterator may be invalidated but not the pointer.
3493 typedef const TypePromotionAction *ConstRestorationPt;
3494 /// Advocate every changes made in that transaction.
3496 /// Undo all the changes made after the given point.
3497 void rollback(ConstRestorationPt Point);
3498 /// Get the current restoration point.
3499 ConstRestorationPt getRestorationPoint() const;
3501 /// \name API for IR modification with state keeping to support rollback.
3503 /// Same as Instruction::setOperand.
3504 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3505 /// Same as Instruction::eraseFromParent.
3506 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3507 /// Same as Value::replaceAllUsesWith.
3508 void replaceAllUsesWith(Instruction *Inst, Value *New);
3509 /// Same as Value::mutateType.
3510 void mutateType(Instruction *Inst, Type *NewTy);
3511 /// Same as IRBuilder::createTrunc.
3512 Value *createTrunc(Instruction *Opnd, Type *Ty);
3513 /// Same as IRBuilder::createSExt.
3514 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3515 /// Same as IRBuilder::createZExt.
3516 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3517 /// Same as Instruction::moveBefore.
3518 void moveBefore(Instruction *Inst, Instruction *Before);
3522 /// The ordered list of actions made so far.
3523 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3524 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
3527 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3530 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
3533 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3536 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
3539 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3541 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3544 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3545 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3548 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3550 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3551 Value *Val = Ptr->getBuiltValue();
3552 Actions.push_back(std::move(Ptr));
3556 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3557 Value *Opnd, Type *Ty) {
3558 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3559 Value *Val = Ptr->getBuiltValue();
3560 Actions.push_back(std::move(Ptr));
3564 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3565 Value *Opnd, Type *Ty) {
3566 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3567 Value *Val = Ptr->getBuiltValue();
3568 Actions.push_back(std::move(Ptr));
3572 void TypePromotionTransaction::moveBefore(Instruction *Inst,
3573 Instruction *Before) {
3575 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
3578 TypePromotionTransaction::ConstRestorationPt
3579 TypePromotionTransaction::getRestorationPoint() const {
3580 return !Actions.empty() ? Actions.back().get() : nullptr;
3583 void TypePromotionTransaction::commit() {
3584 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
3590 void TypePromotionTransaction::rollback(
3591 TypePromotionTransaction::ConstRestorationPt Point) {
3592 while (!Actions.empty() && Point != Actions.back().get()) {
3593 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3598 /// \brief A helper class for matching addressing modes.
3600 /// This encapsulates the logic for matching the target-legal addressing modes.
3601 class AddressingModeMatcher {
3602 SmallVectorImpl<Instruction*> &AddrModeInsts;
3603 const TargetMachine &TM;
3604 const TargetLowering &TLI;
3605 const DataLayout &DL;
3607 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3608 /// the memory instruction that we're computing this address for.
3611 Instruction *MemoryInst;
3613 /// This is the addressing mode that we're building up. This is
3614 /// part of the return value of this addressing mode matching stuff.
3615 ExtAddrMode &AddrMode;
3617 /// The instructions inserted by other CodeGenPrepare optimizations.
3618 const SetOfInstrs &InsertedInsts;
3619 /// A map from the instructions to their type before promotion.
3620 InstrToOrigTy &PromotedInsts;
3621 /// The ongoing transaction where every action should be registered.
3622 TypePromotionTransaction &TPT;
3624 /// This is set to true when we should not do profitability checks.
3625 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3626 bool IgnoreProfitability;
3628 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
3629 const TargetMachine &TM, Type *AT, unsigned AS,
3630 Instruction *MI, ExtAddrMode &AM,
3631 const SetOfInstrs &InsertedInsts,
3632 InstrToOrigTy &PromotedInsts,
3633 TypePromotionTransaction &TPT)
3634 : AddrModeInsts(AMI), TM(TM),
3635 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
3636 ->getTargetLowering()),
3637 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3638 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3639 PromotedInsts(PromotedInsts), TPT(TPT) {
3640 IgnoreProfitability = false;
3644 /// Find the maximal addressing mode that a load/store of V can fold,
3645 /// give an access type of AccessTy. This returns a list of involved
3646 /// instructions in AddrModeInsts.
3647 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3649 /// \p PromotedInsts maps the instructions to their type before promotion.
3650 /// \p The ongoing transaction where every action should be registered.
3651 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
3652 Instruction *MemoryInst,
3653 SmallVectorImpl<Instruction*> &AddrModeInsts,
3654 const TargetMachine &TM,
3655 const SetOfInstrs &InsertedInsts,
3656 InstrToOrigTy &PromotedInsts,
3657 TypePromotionTransaction &TPT) {
3660 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
3661 MemoryInst, Result, InsertedInsts,
3662 PromotedInsts, TPT).matchAddr(V, 0);
3663 (void)Success; assert(Success && "Couldn't select *anything*?");
3667 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3668 bool matchAddr(Value *V, unsigned Depth);
3669 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
3670 bool *MovedAway = nullptr);
3671 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3672 ExtAddrMode &AMBefore,
3673 ExtAddrMode &AMAfter);
3674 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3675 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3676 Value *PromotedOperand) const;
3679 /// Try adding ScaleReg*Scale to the current addressing mode.
3680 /// Return true and update AddrMode if this addr mode is legal for the target,
3682 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3684 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3685 // mode. Just process that directly.
3687 return matchAddr(ScaleReg, Depth);
3689 // If the scale is 0, it takes nothing to add this.
3693 // If we already have a scale of this value, we can add to it, otherwise, we
3694 // need an available scale field.
3695 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3698 ExtAddrMode TestAddrMode = AddrMode;
3700 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3701 // [A+B + A*7] -> [B+A*8].
3702 TestAddrMode.Scale += Scale;
3703 TestAddrMode.ScaledReg = ScaleReg;
3705 // If the new address isn't legal, bail out.
3706 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3709 // It was legal, so commit it.
3710 AddrMode = TestAddrMode;
3712 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3713 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3714 // X*Scale + C*Scale to addr mode.
3715 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3716 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3717 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3718 TestAddrMode.ScaledReg = AddLHS;
3719 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
3721 // If this addressing mode is legal, commit it and remember that we folded
3722 // this instruction.
3723 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3724 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3725 AddrMode = TestAddrMode;
3730 // Otherwise, not (x+c)*scale, just return what we have.
3734 /// This is a little filter, which returns true if an addressing computation
3735 /// involving I might be folded into a load/store accessing it.
3736 /// This doesn't need to be perfect, but needs to accept at least
3737 /// the set of instructions that MatchOperationAddr can.
3738 static bool MightBeFoldableInst(Instruction *I) {
3739 switch (I->getOpcode()) {
3740 case Instruction::BitCast:
3741 case Instruction::AddrSpaceCast:
3742 // Don't touch identity bitcasts.
3743 if (I->getType() == I->getOperand(0)->getType())
3745 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3746 case Instruction::PtrToInt:
3747 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3749 case Instruction::IntToPtr:
3750 // We know the input is intptr_t, so this is foldable.
3752 case Instruction::Add:
3754 case Instruction::Mul:
3755 case Instruction::Shl:
3756 // Can only handle X*C and X << C.
3757 return isa<ConstantInt>(I->getOperand(1));
3758 case Instruction::GetElementPtr:
3765 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3766 /// \note \p Val is assumed to be the product of some type promotion.
3767 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3768 /// to be legal, as the non-promoted value would have had the same state.
3769 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3770 const DataLayout &DL, Value *Val) {
3771 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3774 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3775 // If the ISDOpcode is undefined, it was undefined before the promotion.
3778 // Otherwise, check if the promoted instruction is legal or not.
3779 return TLI.isOperationLegalOrCustom(
3780 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
3783 /// \brief Hepler class to perform type promotion.
3784 class TypePromotionHelper {
3785 /// \brief Utility function to check whether or not a sign or zero extension
3786 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3787 /// either using the operands of \p Inst or promoting \p Inst.
3788 /// The type of the extension is defined by \p IsSExt.
3789 /// In other words, check if:
3790 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
3791 /// #1 Promotion applies:
3792 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
3793 /// #2 Operand reuses:
3794 /// ext opnd1 to ConsideredExtType.
3795 /// \p PromotedInsts maps the instructions to their type before promotion.
3796 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3797 const InstrToOrigTy &PromotedInsts, bool IsSExt);
3799 /// \brief Utility function to determine if \p OpIdx should be promoted when
3800 /// promoting \p Inst.
3801 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
3802 return !(isa<SelectInst>(Inst) && OpIdx == 0);
3805 /// \brief Utility function to promote the operand of \p Ext when this
3806 /// operand is a promotable trunc or sext or zext.
3807 /// \p PromotedInsts maps the instructions to their type before promotion.
3808 /// \p CreatedInstsCost[out] contains the cost of all instructions
3809 /// created to promote the operand of Ext.
3810 /// Newly added extensions are inserted in \p Exts.
3811 /// Newly added truncates are inserted in \p Truncs.
3812 /// Should never be called directly.
3813 /// \return The promoted value which is used instead of Ext.
3814 static Value *promoteOperandForTruncAndAnyExt(
3815 Instruction *Ext, TypePromotionTransaction &TPT,
3816 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3817 SmallVectorImpl<Instruction *> *Exts,
3818 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
3820 /// \brief Utility function to promote the operand of \p Ext when this
3821 /// operand is promotable and is not a supported trunc or sext.
3822 /// \p PromotedInsts maps the instructions to their type before promotion.
3823 /// \p CreatedInstsCost[out] contains the cost of all the instructions
3824 /// created to promote the operand of Ext.
3825 /// Newly added extensions are inserted in \p Exts.
3826 /// Newly added truncates are inserted in \p Truncs.
3827 /// Should never be called directly.
3828 /// \return The promoted value which is used instead of Ext.
3829 static Value *promoteOperandForOther(Instruction *Ext,
3830 TypePromotionTransaction &TPT,
3831 InstrToOrigTy &PromotedInsts,
3832 unsigned &CreatedInstsCost,
3833 SmallVectorImpl<Instruction *> *Exts,
3834 SmallVectorImpl<Instruction *> *Truncs,
3835 const TargetLowering &TLI, bool IsSExt);
3837 /// \see promoteOperandForOther.
3838 static Value *signExtendOperandForOther(
3839 Instruction *Ext, TypePromotionTransaction &TPT,
3840 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3841 SmallVectorImpl<Instruction *> *Exts,
3842 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3843 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3844 Exts, Truncs, TLI, true);
3847 /// \see promoteOperandForOther.
3848 static Value *zeroExtendOperandForOther(
3849 Instruction *Ext, TypePromotionTransaction &TPT,
3850 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3851 SmallVectorImpl<Instruction *> *Exts,
3852 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3853 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3854 Exts, Truncs, TLI, false);
3858 /// Type for the utility function that promotes the operand of Ext.
3859 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
3860 InstrToOrigTy &PromotedInsts,
3861 unsigned &CreatedInstsCost,
3862 SmallVectorImpl<Instruction *> *Exts,
3863 SmallVectorImpl<Instruction *> *Truncs,
3864 const TargetLowering &TLI);
3865 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3866 /// action to promote the operand of \p Ext instead of using Ext.
3867 /// \return NULL if no promotable action is possible with the current
3869 /// \p InsertedInsts keeps track of all the instructions inserted by the
3870 /// other CodeGenPrepare optimizations. This information is important
3871 /// because we do not want to promote these instructions as CodeGenPrepare
3872 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3873 /// \p PromotedInsts maps the instructions to their type before promotion.
3874 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
3875 const TargetLowering &TLI,
3876 const InstrToOrigTy &PromotedInsts);
3879 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
3880 Type *ConsideredExtType,
3881 const InstrToOrigTy &PromotedInsts,
3883 // The promotion helper does not know how to deal with vector types yet.
3884 // To be able to fix that, we would need to fix the places where we
3885 // statically extend, e.g., constants and such.
3886 if (Inst->getType()->isVectorTy())
3889 // We can always get through zext.
3890 if (isa<ZExtInst>(Inst))
3893 // sext(sext) is ok too.
3894 if (IsSExt && isa<SExtInst>(Inst))
3897 // We can get through binary operator, if it is legal. In other words, the
3898 // binary operator must have a nuw or nsw flag.
3899 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3900 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3901 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3902 (IsSExt && BinOp->hasNoSignedWrap())))
3905 // Check if we can do the following simplification.
3906 // ext(trunc(opnd)) --> ext(opnd)
3907 if (!isa<TruncInst>(Inst))
3910 Value *OpndVal = Inst->getOperand(0);
3911 // Check if we can use this operand in the extension.
3912 // If the type is larger than the result type of the extension, we cannot.
3913 if (!OpndVal->getType()->isIntegerTy() ||
3914 OpndVal->getType()->getIntegerBitWidth() >
3915 ConsideredExtType->getIntegerBitWidth())
3918 // If the operand of the truncate is not an instruction, we will not have
3919 // any information on the dropped bits.
3920 // (Actually we could for constant but it is not worth the extra logic).
3921 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3925 // Check if the source of the type is narrow enough.
3926 // I.e., check that trunc just drops extended bits of the same kind of
3928 // #1 get the type of the operand and check the kind of the extended bits.
3929 const Type *OpndType;
3930 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3931 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3932 OpndType = It->second.getPointer();
3933 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3934 OpndType = Opnd->getOperand(0)->getType();
3938 // #2 check that the truncate just drops extended bits.
3939 return Inst->getType()->getIntegerBitWidth() >=
3940 OpndType->getIntegerBitWidth();
3943 TypePromotionHelper::Action TypePromotionHelper::getAction(
3944 Instruction *Ext, const SetOfInstrs &InsertedInsts,
3945 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3946 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3947 "Unexpected instruction type");
3948 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3949 Type *ExtTy = Ext->getType();
3950 bool IsSExt = isa<SExtInst>(Ext);
3951 // If the operand of the extension is not an instruction, we cannot
3953 // If it, check we can get through.
3954 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3957 // Do not promote if the operand has been added by codegenprepare.
3958 // Otherwise, it means we are undoing an optimization that is likely to be
3959 // redone, thus causing potential infinite loop.
3960 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3963 // SExt or Trunc instructions.
3964 // Return the related handler.
3965 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3966 isa<ZExtInst>(ExtOpnd))
3967 return promoteOperandForTruncAndAnyExt;
3969 // Regular instruction.
3970 // Abort early if we will have to insert non-free instructions.
3971 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
3973 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3976 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3977 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
3978 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3979 SmallVectorImpl<Instruction *> *Exts,
3980 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3981 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3982 // get through it and this method should not be called.
3983 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
3984 Value *ExtVal = SExt;
3985 bool HasMergedNonFreeExt = false;
3986 if (isa<ZExtInst>(SExtOpnd)) {
3987 // Replace s|zext(zext(opnd))
3989 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
3991 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3992 TPT.replaceAllUsesWith(SExt, ZExt);
3993 TPT.eraseInstruction(SExt);
3996 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3998 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4000 CreatedInstsCost = 0;
4002 // Remove dead code.
4003 if (SExtOpnd->use_empty())
4004 TPT.eraseInstruction(SExtOpnd);
4006 // Check if the extension is still needed.
4007 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4008 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4011 Exts->push_back(ExtInst);
4012 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4017 // At this point we have: ext ty opnd to ty.
4018 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4019 Value *NextVal = ExtInst->getOperand(0);
4020 TPT.eraseInstruction(ExtInst, NextVal);
4024 Value *TypePromotionHelper::promoteOperandForOther(
4025 Instruction *Ext, TypePromotionTransaction &TPT,
4026 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4027 SmallVectorImpl<Instruction *> *Exts,
4028 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4030 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4031 // get through it and this method should not be called.
4032 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4033 CreatedInstsCost = 0;
4034 if (!ExtOpnd->hasOneUse()) {
4035 // ExtOpnd will be promoted.
4036 // All its uses, but Ext, will need to use a truncated value of the
4037 // promoted version.
4038 // Create the truncate now.
4039 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4040 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4041 ITrunc->removeFromParent();
4042 // Insert it just after the definition.
4043 ITrunc->insertAfter(ExtOpnd);
4045 Truncs->push_back(ITrunc);
4048 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4049 // Restore the operand of Ext (which has been replaced by the previous call
4050 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4051 TPT.setOperand(Ext, 0, ExtOpnd);
4054 // Get through the Instruction:
4055 // 1. Update its type.
4056 // 2. Replace the uses of Ext by Inst.
4057 // 3. Extend each operand that needs to be extended.
4059 // Remember the original type of the instruction before promotion.
4060 // This is useful to know that the high bits are sign extended bits.
4061 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
4062 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
4064 TPT.mutateType(ExtOpnd, Ext->getType());
4066 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4068 Instruction *ExtForOpnd = Ext;
4070 DEBUG(dbgs() << "Propagate Ext to operands\n");
4071 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4073 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4074 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4075 !shouldExtOperand(ExtOpnd, OpIdx)) {
4076 DEBUG(dbgs() << "No need to propagate\n");
4079 // Check if we can statically extend the operand.
4080 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4081 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4082 DEBUG(dbgs() << "Statically extend\n");
4083 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4084 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4085 : Cst->getValue().zext(BitWidth);
4086 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4089 // UndefValue are typed, so we have to statically sign extend them.
4090 if (isa<UndefValue>(Opnd)) {
4091 DEBUG(dbgs() << "Statically extend\n");
4092 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4096 // Otherwise we have to explicity sign extend the operand.
4097 // Check if Ext was reused to extend an operand.
4099 // If yes, create a new one.
4100 DEBUG(dbgs() << "More operands to ext\n");
4101 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4102 : TPT.createZExt(Ext, Opnd, Ext->getType());
4103 if (!isa<Instruction>(ValForExtOpnd)) {
4104 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4107 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4110 Exts->push_back(ExtForOpnd);
4111 TPT.setOperand(ExtForOpnd, 0, Opnd);
4113 // Move the sign extension before the insertion point.
4114 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4115 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4116 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
4117 // If more sext are required, new instructions will have to be created.
4118 ExtForOpnd = nullptr;
4120 if (ExtForOpnd == Ext) {
4121 DEBUG(dbgs() << "Extension is useless now\n");
4122 TPT.eraseInstruction(Ext);
4127 /// Check whether or not promoting an instruction to a wider type is profitable.
4128 /// \p NewCost gives the cost of extension instructions created by the
4130 /// \p OldCost gives the cost of extension instructions before the promotion
4131 /// plus the number of instructions that have been
4132 /// matched in the addressing mode the promotion.
4133 /// \p PromotedOperand is the value that has been promoted.
4134 /// \return True if the promotion is profitable, false otherwise.
4135 bool AddressingModeMatcher::isPromotionProfitable(
4136 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4137 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
4138 // The cost of the new extensions is greater than the cost of the
4139 // old extension plus what we folded.
4140 // This is not profitable.
4141 if (NewCost > OldCost)
4143 if (NewCost < OldCost)
4145 // The promotion is neutral but it may help folding the sign extension in
4146 // loads for instance.
4147 // Check that we did not create an illegal instruction.
4148 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4151 /// Given an instruction or constant expr, see if we can fold the operation
4152 /// into the addressing mode. If so, update the addressing mode and return
4153 /// true, otherwise return false without modifying AddrMode.
4154 /// If \p MovedAway is not NULL, it contains the information of whether or
4155 /// not AddrInst has to be folded into the addressing mode on success.
4156 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4157 /// because it has been moved away.
4158 /// Thus AddrInst must not be added in the matched instructions.
4159 /// This state can happen when AddrInst is a sext, since it may be moved away.
4160 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
4161 /// not be referenced anymore.
4162 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4165 // Avoid exponential behavior on extremely deep expression trees.
4166 if (Depth >= 5) return false;
4168 // By default, all matched instructions stay in place.
4173 case Instruction::PtrToInt:
4174 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4175 return matchAddr(AddrInst->getOperand(0), Depth);
4176 case Instruction::IntToPtr: {
4177 auto AS = AddrInst->getType()->getPointerAddressSpace();
4178 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4179 // This inttoptr is a no-op if the integer type is pointer sized.
4180 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4181 return matchAddr(AddrInst->getOperand(0), Depth);
4184 case Instruction::BitCast:
4185 // BitCast is always a noop, and we can handle it as long as it is
4186 // int->int or pointer->pointer (we don't want int<->fp or something).
4187 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
4188 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
4189 // Don't touch identity bitcasts. These were probably put here by LSR,
4190 // and we don't want to mess around with them. Assume it knows what it
4192 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4193 return matchAddr(AddrInst->getOperand(0), Depth);
4195 case Instruction::AddrSpaceCast: {
4197 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4198 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4199 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
4200 return matchAddr(AddrInst->getOperand(0), Depth);
4203 case Instruction::Add: {
4204 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4205 ExtAddrMode BackupAddrMode = AddrMode;
4206 unsigned OldSize = AddrModeInsts.size();
4207 // Start a transaction at this point.
4208 // The LHS may match but not the RHS.
4209 // Therefore, we need a higher level restoration point to undo partially
4210 // matched operation.
4211 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4212 TPT.getRestorationPoint();
4214 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
4215 matchAddr(AddrInst->getOperand(0), Depth+1))
4218 // Restore the old addr mode info.
4219 AddrMode = BackupAddrMode;
4220 AddrModeInsts.resize(OldSize);
4221 TPT.rollback(LastKnownGood);
4223 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
4224 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4225 matchAddr(AddrInst->getOperand(1), Depth+1))
4228 // Otherwise we definitely can't merge the ADD in.
4229 AddrMode = BackupAddrMode;
4230 AddrModeInsts.resize(OldSize);
4231 TPT.rollback(LastKnownGood);
4234 //case Instruction::Or:
4235 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4237 case Instruction::Mul:
4238 case Instruction::Shl: {
4239 // Can only handle X*C and X << C.
4240 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4243 int64_t Scale = RHS->getSExtValue();
4244 if (Opcode == Instruction::Shl)
4245 Scale = 1LL << Scale;
4247 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4249 case Instruction::GetElementPtr: {
4250 // Scan the GEP. We check it if it contains constant offsets and at most
4251 // one variable offset.
4252 int VariableOperand = -1;
4253 unsigned VariableScale = 0;
4255 int64_t ConstantOffset = 0;
4256 gep_type_iterator GTI = gep_type_begin(AddrInst);
4257 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4258 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
4259 const StructLayout *SL = DL.getStructLayout(STy);
4261 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4262 ConstantOffset += SL->getElementOffset(Idx);
4264 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
4265 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4266 ConstantOffset += CI->getSExtValue()*TypeSize;
4267 } else if (TypeSize) { // Scales of zero don't do anything.
4268 // We only allow one variable index at the moment.
4269 if (VariableOperand != -1)
4272 // Remember the variable index.
4273 VariableOperand = i;
4274 VariableScale = TypeSize;
4279 // A common case is for the GEP to only do a constant offset. In this case,
4280 // just add it to the disp field and check validity.
4281 if (VariableOperand == -1) {
4282 AddrMode.BaseOffs += ConstantOffset;
4283 if (ConstantOffset == 0 ||
4284 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4285 // Check to see if we can fold the base pointer in too.
4286 if (matchAddr(AddrInst->getOperand(0), Depth+1))
4289 AddrMode.BaseOffs -= ConstantOffset;
4293 // Save the valid addressing mode in case we can't match.
4294 ExtAddrMode BackupAddrMode = AddrMode;
4295 unsigned OldSize = AddrModeInsts.size();
4297 // See if the scale and offset amount is valid for this target.
4298 AddrMode.BaseOffs += ConstantOffset;
4300 // Match the base operand of the GEP.
4301 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
4302 // If it couldn't be matched, just stuff the value in a register.
4303 if (AddrMode.HasBaseReg) {
4304 AddrMode = BackupAddrMode;
4305 AddrModeInsts.resize(OldSize);
4308 AddrMode.HasBaseReg = true;
4309 AddrMode.BaseReg = AddrInst->getOperand(0);
4312 // Match the remaining variable portion of the GEP.
4313 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4315 // If it couldn't be matched, try stuffing the base into a register
4316 // instead of matching it, and retrying the match of the scale.
4317 AddrMode = BackupAddrMode;
4318 AddrModeInsts.resize(OldSize);
4319 if (AddrMode.HasBaseReg)
4321 AddrMode.HasBaseReg = true;
4322 AddrMode.BaseReg = AddrInst->getOperand(0);
4323 AddrMode.BaseOffs += ConstantOffset;
4324 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4325 VariableScale, Depth)) {
4326 // If even that didn't work, bail.
4327 AddrMode = BackupAddrMode;
4328 AddrModeInsts.resize(OldSize);
4335 case Instruction::SExt:
4336 case Instruction::ZExt: {
4337 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4341 // Try to move this ext out of the way of the addressing mode.
4342 // Ask for a method for doing so.
4343 TypePromotionHelper::Action TPH =
4344 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4348 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4349 TPT.getRestorationPoint();
4350 unsigned CreatedInstsCost = 0;
4351 unsigned ExtCost = !TLI.isExtFree(Ext);
4352 Value *PromotedOperand =
4353 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4354 // SExt has been moved away.
4355 // Thus either it will be rematched later in the recursive calls or it is
4356 // gone. Anyway, we must not fold it into the addressing mode at this point.
4360 // addr = gep base, idx
4362 // promotedOpnd = ext opnd <- no match here
4363 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4364 // addr = gep base, op <- match
4368 assert(PromotedOperand &&
4369 "TypePromotionHelper should have filtered out those cases");
4371 ExtAddrMode BackupAddrMode = AddrMode;
4372 unsigned OldSize = AddrModeInsts.size();
4374 if (!matchAddr(PromotedOperand, Depth) ||
4375 // The total of the new cost is equal to the cost of the created
4377 // The total of the old cost is equal to the cost of the extension plus
4378 // what we have saved in the addressing mode.
4379 !isPromotionProfitable(CreatedInstsCost,
4380 ExtCost + (AddrModeInsts.size() - OldSize),
4382 AddrMode = BackupAddrMode;
4383 AddrModeInsts.resize(OldSize);
4384 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
4385 TPT.rollback(LastKnownGood);
4394 /// If we can, try to add the value of 'Addr' into the current addressing mode.
4395 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4396 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
4399 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4400 // Start a transaction at this point that we will rollback if the matching
4402 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4403 TPT.getRestorationPoint();
4404 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4405 // Fold in immediates if legal for the target.
4406 AddrMode.BaseOffs += CI->getSExtValue();
4407 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4409 AddrMode.BaseOffs -= CI->getSExtValue();
4410 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4411 // If this is a global variable, try to fold it into the addressing mode.
4412 if (!AddrMode.BaseGV) {
4413 AddrMode.BaseGV = GV;
4414 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4416 AddrMode.BaseGV = nullptr;
4418 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4419 ExtAddrMode BackupAddrMode = AddrMode;
4420 unsigned OldSize = AddrModeInsts.size();
4422 // Check to see if it is possible to fold this operation.
4423 bool MovedAway = false;
4424 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4425 // This instruction may have been moved away. If so, there is nothing
4429 // Okay, it's possible to fold this. Check to see if it is actually
4430 // *profitable* to do so. We use a simple cost model to avoid increasing
4431 // register pressure too much.
4432 if (I->hasOneUse() ||
4433 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4434 AddrModeInsts.push_back(I);
4438 // It isn't profitable to do this, roll back.
4439 //cerr << "NOT FOLDING: " << *I;
4440 AddrMode = BackupAddrMode;
4441 AddrModeInsts.resize(OldSize);
4442 TPT.rollback(LastKnownGood);
4444 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4445 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4447 TPT.rollback(LastKnownGood);
4448 } else if (isa<ConstantPointerNull>(Addr)) {
4449 // Null pointer gets folded without affecting the addressing mode.
4453 // Worse case, the target should support [reg] addressing modes. :)
4454 if (!AddrMode.HasBaseReg) {
4455 AddrMode.HasBaseReg = true;
4456 AddrMode.BaseReg = Addr;
4457 // Still check for legality in case the target supports [imm] but not [i+r].
4458 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4460 AddrMode.HasBaseReg = false;
4461 AddrMode.BaseReg = nullptr;
4464 // If the base register is already taken, see if we can do [r+r].
4465 if (AddrMode.Scale == 0) {
4467 AddrMode.ScaledReg = Addr;
4468 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4471 AddrMode.ScaledReg = nullptr;
4474 TPT.rollback(LastKnownGood);
4478 /// Check to see if all uses of OpVal by the specified inline asm call are due
4479 /// to memory operands. If so, return true, otherwise return false.
4480 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
4481 const TargetMachine &TM) {
4482 const Function *F = CI->getParent()->getParent();
4483 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
4484 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
4485 TargetLowering::AsmOperandInfoVector TargetConstraints =
4486 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
4487 ImmutableCallSite(CI));
4488 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4489 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4491 // Compute the constraint code and ConstraintType to use.
4492 TLI->ComputeConstraintToUse(OpInfo, SDValue());
4494 // If this asm operand is our Value*, and if it isn't an indirect memory
4495 // operand, we can't fold it!
4496 if (OpInfo.CallOperandVal == OpVal &&
4497 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4498 !OpInfo.isIndirect))
4505 /// Recursively walk all the uses of I until we find a memory use.
4506 /// If we find an obviously non-foldable instruction, return true.
4507 /// Add the ultimately found memory instructions to MemoryUses.
4508 static bool FindAllMemoryUses(
4510 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
4511 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
4512 // If we already considered this instruction, we're done.
4513 if (!ConsideredInsts.insert(I).second)
4516 // If this is an obviously unfoldable instruction, bail out.
4517 if (!MightBeFoldableInst(I))
4520 // Loop over all the uses, recursively processing them.
4521 for (Use &U : I->uses()) {
4522 Instruction *UserI = cast<Instruction>(U.getUser());
4524 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4525 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4529 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4530 unsigned opNo = U.getOperandNo();
4531 if (opNo == 0) return true; // Storing addr, not into addr.
4532 MemoryUses.push_back(std::make_pair(SI, opNo));
4536 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
4537 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4538 if (!IA) return true;
4540 // If this is a memory operand, we're cool, otherwise bail out.
4541 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
4546 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
4553 /// Return true if Val is already known to be live at the use site that we're
4554 /// folding it into. If so, there is no cost to include it in the addressing
4555 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4556 /// instruction already.
4557 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4558 Value *KnownLive2) {
4559 // If Val is either of the known-live values, we know it is live!
4560 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4563 // All values other than instructions and arguments (e.g. constants) are live.
4564 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4566 // If Val is a constant sized alloca in the entry block, it is live, this is
4567 // true because it is just a reference to the stack/frame pointer, which is
4568 // live for the whole function.
4569 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4570 if (AI->isStaticAlloca())
4573 // Check to see if this value is already used in the memory instruction's
4574 // block. If so, it's already live into the block at the very least, so we
4575 // can reasonably fold it.
4576 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4579 /// It is possible for the addressing mode of the machine to fold the specified
4580 /// instruction into a load or store that ultimately uses it.
4581 /// However, the specified instruction has multiple uses.
4582 /// Given this, it may actually increase register pressure to fold it
4583 /// into the load. For example, consider this code:
4587 /// use(Y) -> nonload/store
4591 /// In this case, Y has multiple uses, and can be folded into the load of Z
4592 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4593 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4594 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4595 /// number of computations either.
4597 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4598 /// X was live across 'load Z' for other reasons, we actually *would* want to
4599 /// fold the addressing mode in the Z case. This would make Y die earlier.
4600 bool AddressingModeMatcher::
4601 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4602 ExtAddrMode &AMAfter) {
4603 if (IgnoreProfitability) return true;
4605 // AMBefore is the addressing mode before this instruction was folded into it,
4606 // and AMAfter is the addressing mode after the instruction was folded. Get
4607 // the set of registers referenced by AMAfter and subtract out those
4608 // referenced by AMBefore: this is the set of values which folding in this
4609 // address extends the lifetime of.
4611 // Note that there are only two potential values being referenced here,
4612 // BaseReg and ScaleReg (global addresses are always available, as are any
4613 // folded immediates).
4614 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4616 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4617 // lifetime wasn't extended by adding this instruction.
4618 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4620 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4621 ScaledReg = nullptr;
4623 // If folding this instruction (and it's subexprs) didn't extend any live
4624 // ranges, we're ok with it.
4625 if (!BaseReg && !ScaledReg)
4628 // If all uses of this instruction are ultimately load/store/inlineasm's,
4629 // check to see if their addressing modes will include this instruction. If
4630 // so, we can fold it into all uses, so it doesn't matter if it has multiple
4632 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4633 SmallPtrSet<Instruction*, 16> ConsideredInsts;
4634 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
4635 return false; // Has a non-memory, non-foldable use!
4637 // Now that we know that all uses of this instruction are part of a chain of
4638 // computation involving only operations that could theoretically be folded
4639 // into a memory use, loop over each of these uses and see if they could
4640 // *actually* fold the instruction.
4641 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4642 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4643 Instruction *User = MemoryUses[i].first;
4644 unsigned OpNo = MemoryUses[i].second;
4646 // Get the access type of this use. If the use isn't a pointer, we don't
4647 // know what it accesses.
4648 Value *Address = User->getOperand(OpNo);
4649 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4652 Type *AddressAccessTy = AddrTy->getElementType();
4653 unsigned AS = AddrTy->getAddressSpace();
4655 // Do a match against the root of this address, ignoring profitability. This
4656 // will tell us if the addressing mode for the memory operation will
4657 // *actually* cover the shared instruction.
4659 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4660 TPT.getRestorationPoint();
4661 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
4662 MemoryInst, Result, InsertedInsts,
4663 PromotedInsts, TPT);
4664 Matcher.IgnoreProfitability = true;
4665 bool Success = Matcher.matchAddr(Address, 0);
4666 (void)Success; assert(Success && "Couldn't select *anything*?");
4668 // The match was to check the profitability, the changes made are not
4669 // part of the original matcher. Therefore, they should be dropped
4670 // otherwise the original matcher will not present the right state.
4671 TPT.rollback(LastKnownGood);
4673 // If the match didn't cover I, then it won't be shared by it.
4674 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
4675 I) == MatchedAddrModeInsts.end())
4678 MatchedAddrModeInsts.clear();
4684 } // end anonymous namespace
4686 /// Return true if the specified values are defined in a
4687 /// different basic block than BB.
4688 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4689 if (Instruction *I = dyn_cast<Instruction>(V))
4690 return I->getParent() != BB;
4694 /// Load and Store Instructions often have addressing modes that can do
4695 /// significant amounts of computation. As such, instruction selection will try
4696 /// to get the load or store to do as much computation as possible for the
4697 /// program. The problem is that isel can only see within a single block. As
4698 /// such, we sink as much legal addressing mode work into the block as possible.
4700 /// This method is used to optimize both load/store and inline asms with memory
4702 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
4703 Type *AccessTy, unsigned AddrSpace) {
4706 // Try to collapse single-value PHI nodes. This is necessary to undo
4707 // unprofitable PRE transformations.
4708 SmallVector<Value*, 8> worklist;
4709 SmallPtrSet<Value*, 16> Visited;
4710 worklist.push_back(Addr);
4712 // Use a worklist to iteratively look through PHI nodes, and ensure that
4713 // the addressing mode obtained from the non-PHI roots of the graph
4715 Value *Consensus = nullptr;
4716 unsigned NumUsesConsensus = 0;
4717 bool IsNumUsesConsensusValid = false;
4718 SmallVector<Instruction*, 16> AddrModeInsts;
4719 ExtAddrMode AddrMode;
4720 TypePromotionTransaction TPT;
4721 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4722 TPT.getRestorationPoint();
4723 while (!worklist.empty()) {
4724 Value *V = worklist.back();
4725 worklist.pop_back();
4727 // Break use-def graph loops.
4728 if (!Visited.insert(V).second) {
4729 Consensus = nullptr;
4733 // For a PHI node, push all of its incoming values.
4734 if (PHINode *P = dyn_cast<PHINode>(V)) {
4735 for (Value *IncValue : P->incoming_values())
4736 worklist.push_back(IncValue);
4740 // For non-PHIs, determine the addressing mode being computed.
4741 SmallVector<Instruction*, 16> NewAddrModeInsts;
4742 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4743 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
4744 InsertedInsts, PromotedInsts, TPT);
4746 // This check is broken into two cases with very similar code to avoid using
4747 // getNumUses() as much as possible. Some values have a lot of uses, so
4748 // calling getNumUses() unconditionally caused a significant compile-time
4752 AddrMode = NewAddrMode;
4753 AddrModeInsts = NewAddrModeInsts;
4755 } else if (NewAddrMode == AddrMode) {
4756 if (!IsNumUsesConsensusValid) {
4757 NumUsesConsensus = Consensus->getNumUses();
4758 IsNumUsesConsensusValid = true;
4761 // Ensure that the obtained addressing mode is equivalent to that obtained
4762 // for all other roots of the PHI traversal. Also, when choosing one
4763 // such root as representative, select the one with the most uses in order
4764 // to keep the cost modeling heuristics in AddressingModeMatcher
4766 unsigned NumUses = V->getNumUses();
4767 if (NumUses > NumUsesConsensus) {
4769 NumUsesConsensus = NumUses;
4770 AddrModeInsts = NewAddrModeInsts;
4775 Consensus = nullptr;
4779 // If the addressing mode couldn't be determined, or if multiple different
4780 // ones were determined, bail out now.
4782 TPT.rollback(LastKnownGood);
4787 // Check to see if any of the instructions supersumed by this addr mode are
4788 // non-local to I's BB.
4789 bool AnyNonLocal = false;
4790 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
4791 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
4797 // If all the instructions matched are already in this BB, don't do anything.
4799 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
4803 // Insert this computation right after this user. Since our caller is
4804 // scanning from the top of the BB to the bottom, reuse of the expr are
4805 // guaranteed to happen later.
4806 IRBuilder<> Builder(MemoryInst);
4808 // Now that we determined the addressing expression we want to use and know
4809 // that we have to sink it into this block. Check to see if we have already
4810 // done this for some other load/store instr in this block. If so, reuse the
4812 Value *&SunkAddr = SunkAddrs[Addr];
4814 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
4815 << *MemoryInst << "\n");
4816 if (SunkAddr->getType() != Addr->getType())
4817 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4818 } else if (AddrSinkUsingGEPs ||
4819 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
4820 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
4822 // By default, we use the GEP-based method when AA is used later. This
4823 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4824 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4825 << *MemoryInst << "\n");
4826 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4827 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
4829 // First, find the pointer.
4830 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4831 ResultPtr = AddrMode.BaseReg;
4832 AddrMode.BaseReg = nullptr;
4835 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4836 // We can't add more than one pointer together, nor can we scale a
4837 // pointer (both of which seem meaningless).
4838 if (ResultPtr || AddrMode.Scale != 1)
4841 ResultPtr = AddrMode.ScaledReg;
4845 if (AddrMode.BaseGV) {
4849 ResultPtr = AddrMode.BaseGV;
4852 // If the real base value actually came from an inttoptr, then the matcher
4853 // will look through it and provide only the integer value. In that case,
4855 if (!ResultPtr && AddrMode.BaseReg) {
4857 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
4858 AddrMode.BaseReg = nullptr;
4859 } else if (!ResultPtr && AddrMode.Scale == 1) {
4861 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4866 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4867 SunkAddr = Constant::getNullValue(Addr->getType());
4868 } else if (!ResultPtr) {
4872 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4873 Type *I8Ty = Builder.getInt8Ty();
4875 // Start with the base register. Do this first so that subsequent address
4876 // matching finds it last, which will prevent it from trying to match it
4877 // as the scaled value in case it happens to be a mul. That would be
4878 // problematic if we've sunk a different mul for the scale, because then
4879 // we'd end up sinking both muls.
4880 if (AddrMode.BaseReg) {
4881 Value *V = AddrMode.BaseReg;
4882 if (V->getType() != IntPtrTy)
4883 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4888 // Add the scale value.
4889 if (AddrMode.Scale) {
4890 Value *V = AddrMode.ScaledReg;
4891 if (V->getType() == IntPtrTy) {
4893 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4894 cast<IntegerType>(V->getType())->getBitWidth()) {
4895 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4897 // It is only safe to sign extend the BaseReg if we know that the math
4898 // required to create it did not overflow before we extend it. Since
4899 // the original IR value was tossed in favor of a constant back when
4900 // the AddrMode was created we need to bail out gracefully if widths
4901 // do not match instead of extending it.
4902 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4903 if (I && (ResultIndex != AddrMode.BaseReg))
4904 I->eraseFromParent();
4908 if (AddrMode.Scale != 1)
4909 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4912 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4917 // Add in the Base Offset if present.
4918 if (AddrMode.BaseOffs) {
4919 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4921 // We need to add this separately from the scale above to help with
4922 // SDAG consecutive load/store merging.
4923 if (ResultPtr->getType() != I8PtrTy)
4924 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4925 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4932 SunkAddr = ResultPtr;
4934 if (ResultPtr->getType() != I8PtrTy)
4935 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4936 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4939 if (SunkAddr->getType() != Addr->getType())
4940 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4943 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4944 << *MemoryInst << "\n");
4945 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4946 Value *Result = nullptr;
4948 // Start with the base register. Do this first so that subsequent address
4949 // matching finds it last, which will prevent it from trying to match it
4950 // as the scaled value in case it happens to be a mul. That would be
4951 // problematic if we've sunk a different mul for the scale, because then
4952 // we'd end up sinking both muls.
4953 if (AddrMode.BaseReg) {
4954 Value *V = AddrMode.BaseReg;
4955 if (V->getType()->isPointerTy())
4956 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4957 if (V->getType() != IntPtrTy)
4958 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4962 // Add the scale value.
4963 if (AddrMode.Scale) {
4964 Value *V = AddrMode.ScaledReg;
4965 if (V->getType() == IntPtrTy) {
4967 } else if (V->getType()->isPointerTy()) {
4968 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4969 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4970 cast<IntegerType>(V->getType())->getBitWidth()) {
4971 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4973 // It is only safe to sign extend the BaseReg if we know that the math
4974 // required to create it did not overflow before we extend it. Since
4975 // the original IR value was tossed in favor of a constant back when
4976 // the AddrMode was created we need to bail out gracefully if widths
4977 // do not match instead of extending it.
4978 Instruction *I = dyn_cast_or_null<Instruction>(Result);
4979 if (I && (Result != AddrMode.BaseReg))
4980 I->eraseFromParent();
4983 if (AddrMode.Scale != 1)
4984 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4987 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4992 // Add in the BaseGV if present.
4993 if (AddrMode.BaseGV) {
4994 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
4996 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5001 // Add in the Base Offset if present.
5002 if (AddrMode.BaseOffs) {
5003 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
5005 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5011 SunkAddr = Constant::getNullValue(Addr->getType());
5013 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
5016 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
5018 // If we have no uses, recursively delete the value and all dead instructions
5020 if (Repl->use_empty()) {
5021 // This can cause recursive deletion, which can invalidate our iterator.
5022 // Use a WeakVH to hold onto it in case this happens.
5023 WeakVH IterHandle(&*CurInstIterator);
5024 BasicBlock *BB = CurInstIterator->getParent();
5026 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
5028 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
5029 // If the iterator instruction was recursively deleted, start over at the
5030 // start of the block.
5031 CurInstIterator = BB->begin();
5039 /// If there are any memory operands, use OptimizeMemoryInst to sink their
5040 /// address computing into the block when possible / profitable.
5041 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
5042 bool MadeChange = false;
5044 const TargetRegisterInfo *TRI =
5045 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
5046 TargetLowering::AsmOperandInfoVector TargetConstraints =
5047 TLI->ParseConstraints(*DL, TRI, CS);
5049 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5050 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
5052 // Compute the constraint code and ConstraintType to use.
5053 TLI->ComputeConstraintToUse(OpInfo, SDValue());
5055 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5056 OpInfo.isIndirect) {
5057 Value *OpVal = CS->getArgOperand(ArgNo++);
5058 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
5059 } else if (OpInfo.Type == InlineAsm::isInput)
5066 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
5067 /// sign extensions.
5068 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
5069 assert(!Inst->use_empty() && "Input must have at least one use");
5070 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
5071 bool IsSExt = isa<SExtInst>(FirstUser);
5072 Type *ExtTy = FirstUser->getType();
5073 for (const User *U : Inst->users()) {
5074 const Instruction *UI = cast<Instruction>(U);
5075 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
5077 Type *CurTy = UI->getType();
5078 // Same input and output types: Same instruction after CSE.
5082 // If IsSExt is true, we are in this situation:
5084 // b = sext ty1 a to ty2
5085 // c = sext ty1 a to ty3
5086 // Assuming ty2 is shorter than ty3, this could be turned into:
5088 // b = sext ty1 a to ty2
5089 // c = sext ty2 b to ty3
5090 // However, the last sext is not free.
5094 // This is a ZExt, maybe this is free to extend from one type to another.
5095 // In that case, we would not account for a different use.
5098 if (ExtTy->getScalarType()->getIntegerBitWidth() >
5099 CurTy->getScalarType()->getIntegerBitWidth()) {
5107 if (!TLI.isZExtFree(NarrowTy, LargeTy))
5110 // All uses are the same or can be derived from one another for free.
5114 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
5115 /// load instruction.
5116 /// If an ext(load) can be formed, it is returned via \p LI for the load
5117 /// and \p Inst for the extension.
5118 /// Otherwise LI == nullptr and Inst == nullptr.
5119 /// When some promotion happened, \p TPT contains the proper state to
5122 /// \return true when promoting was necessary to expose the ext(load)
5123 /// opportunity, false otherwise.
5127 /// %ld = load i32* %addr
5128 /// %add = add nuw i32 %ld, 4
5129 /// %zext = zext i32 %add to i64
5133 /// %ld = load i32* %addr
5134 /// %zext = zext i32 %ld to i64
5135 /// %add = add nuw i64 %zext, 4
5137 /// Thanks to the promotion, we can match zext(load i32*) to i64.
5138 bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
5139 LoadInst *&LI, Instruction *&Inst,
5140 const SmallVectorImpl<Instruction *> &Exts,
5141 unsigned CreatedInstsCost = 0) {
5142 // Iterate over all the extensions to see if one form an ext(load).
5143 for (auto I : Exts) {
5144 // Check if we directly have ext(load).
5145 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
5147 // No promotion happened here.
5150 // Check whether or not we want to do any promotion.
5151 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
5153 // Get the action to perform the promotion.
5154 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
5155 I, InsertedInsts, *TLI, PromotedInsts);
5156 // Check if we can promote.
5159 // Save the current state.
5160 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5161 TPT.getRestorationPoint();
5162 SmallVector<Instruction *, 4> NewExts;
5163 unsigned NewCreatedInstsCost = 0;
5164 unsigned ExtCost = !TLI->isExtFree(I);
5166 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5167 &NewExts, nullptr, *TLI);
5168 assert(PromotedVal &&
5169 "TypePromotionHelper should have filtered out those cases");
5171 // We would be able to merge only one extension in a load.
5172 // Therefore, if we have more than 1 new extension we heuristically
5173 // cut this search path, because it means we degrade the code quality.
5174 // With exactly 2, the transformation is neutral, because we will merge
5175 // one extension but leave one. However, we optimistically keep going,
5176 // because the new extension may be removed too.
5177 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
5178 TotalCreatedInstsCost -= ExtCost;
5179 if (!StressExtLdPromotion &&
5180 (TotalCreatedInstsCost > 1 ||
5181 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
5182 // The promotion is not profitable, rollback to the previous state.
5183 TPT.rollback(LastKnownGood);
5186 // The promotion is profitable.
5187 // Check if it exposes an ext(load).
5188 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
5189 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5190 // If we have created a new extension, i.e., now we have two
5191 // extensions. We must make sure one of them is merged with
5192 // the load, otherwise we may degrade the code quality.
5193 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
5194 // Promotion happened.
5196 // If this does not help to expose an ext(load) then, rollback.
5197 TPT.rollback(LastKnownGood);
5199 // None of the extension can form an ext(load).
5205 /// Move a zext or sext fed by a load into the same basic block as the load,
5206 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
5207 /// extend into the load.
5208 /// \p I[in/out] the extension may be modified during the process if some
5209 /// promotions apply.
5211 bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
5212 // Try to promote a chain of computation if it allows to form
5213 // an extended load.
5214 TypePromotionTransaction TPT;
5215 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5216 TPT.getRestorationPoint();
5217 SmallVector<Instruction *, 1> Exts;
5219 // Look for a load being extended.
5220 LoadInst *LI = nullptr;
5221 Instruction *OldExt = I;
5222 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
5224 assert(!HasPromoted && !LI && "If we did not match any load instruction "
5225 "the code must remain the same");
5230 // If they're already in the same block, there's nothing to do.
5231 // Make the cheap checks first if we did not promote.
5232 // If we promoted, we need to check if it is indeed profitable.
5233 if (!HasPromoted && LI->getParent() == I->getParent())
5236 EVT VT = TLI->getValueType(*DL, I->getType());
5237 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
5239 // If the load has other users and the truncate is not free, this probably
5240 // isn't worthwhile.
5241 if (!LI->hasOneUse() && TLI &&
5242 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
5243 !TLI->isTruncateFree(I->getType(), LI->getType())) {
5245 TPT.rollback(LastKnownGood);
5249 // Check whether the target supports casts folded into loads.
5251 if (isa<ZExtInst>(I))
5252 LType = ISD::ZEXTLOAD;
5254 assert(isa<SExtInst>(I) && "Unexpected ext type!");
5255 LType = ISD::SEXTLOAD;
5257 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
5259 TPT.rollback(LastKnownGood);
5263 // Move the extend into the same block as the load, so that SelectionDAG
5266 I->removeFromParent();
5272 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
5273 BasicBlock *DefBB = I->getParent();
5275 // If the result of a {s|z}ext and its source are both live out, rewrite all
5276 // other uses of the source with result of extension.
5277 Value *Src = I->getOperand(0);
5278 if (Src->hasOneUse())
5281 // Only do this xform if truncating is free.
5282 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
5285 // Only safe to perform the optimization if the source is also defined in
5287 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
5290 bool DefIsLiveOut = false;
5291 for (User *U : I->users()) {
5292 Instruction *UI = cast<Instruction>(U);
5294 // Figure out which BB this ext is used in.
5295 BasicBlock *UserBB = UI->getParent();
5296 if (UserBB == DefBB) continue;
5297 DefIsLiveOut = true;
5303 // Make sure none of the uses are PHI nodes.
5304 for (User *U : Src->users()) {
5305 Instruction *UI = cast<Instruction>(U);
5306 BasicBlock *UserBB = UI->getParent();
5307 if (UserBB == DefBB) continue;
5308 // Be conservative. We don't want this xform to end up introducing
5309 // reloads just before load / store instructions.
5310 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5314 // InsertedTruncs - Only insert one trunc in each block once.
5315 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5317 bool MadeChange = false;
5318 for (Use &U : Src->uses()) {
5319 Instruction *User = cast<Instruction>(U.getUser());
5321 // Figure out which BB this ext is used in.
5322 BasicBlock *UserBB = User->getParent();
5323 if (UserBB == DefBB) continue;
5325 // Both src and def are live in this block. Rewrite the use.
5326 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5328 if (!InsertedTrunc) {
5329 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5330 assert(InsertPt != UserBB->end());
5331 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
5332 InsertedInsts.insert(InsertedTrunc);
5335 // Replace a use of the {s|z}ext source with a use of the result.
5344 // Find loads whose uses only use some of the loaded value's bits. Add an "and"
5345 // just after the load if the target can fold this into one extload instruction,
5346 // with the hope of eliminating some of the other later "and" instructions using
5347 // the loaded value. "and"s that are made trivially redundant by the insertion
5348 // of the new "and" are removed by this function, while others (e.g. those whose
5349 // path from the load goes through a phi) are left for isel to potentially
5382 // becomes (after a call to optimizeLoadExt for each load):
5386 // x1' = and x1, 0xff
5390 // x2' = and x2, 0xff
5397 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5399 if (!Load->isSimple() ||
5400 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5403 // Skip loads we've already transformed or have no reason to transform.
5404 if (Load->hasOneUse()) {
5405 User *LoadUser = *Load->user_begin();
5406 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
5407 !dyn_cast<PHINode>(LoadUser))
5411 // Look at all uses of Load, looking through phis, to determine how many bits
5412 // of the loaded value are needed.
5413 SmallVector<Instruction *, 8> WorkList;
5414 SmallPtrSet<Instruction *, 16> Visited;
5415 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5416 for (auto *U : Load->users())
5417 WorkList.push_back(cast<Instruction>(U));
5419 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5420 unsigned BitWidth = LoadResultVT.getSizeInBits();
5421 APInt DemandBits(BitWidth, 0);
5422 APInt WidestAndBits(BitWidth, 0);
5424 while (!WorkList.empty()) {
5425 Instruction *I = WorkList.back();
5426 WorkList.pop_back();
5428 // Break use-def graph loops.
5429 if (!Visited.insert(I).second)
5432 // For a PHI node, push all of its users.
5433 if (auto *Phi = dyn_cast<PHINode>(I)) {
5434 for (auto *U : Phi->users())
5435 WorkList.push_back(cast<Instruction>(U));
5439 switch (I->getOpcode()) {
5440 case llvm::Instruction::And: {
5441 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5444 APInt AndBits = AndC->getValue();
5445 DemandBits |= AndBits;
5446 // Keep track of the widest and mask we see.
5447 if (AndBits.ugt(WidestAndBits))
5448 WidestAndBits = AndBits;
5449 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5450 AndsToMaybeRemove.push_back(I);
5454 case llvm::Instruction::Shl: {
5455 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5458 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5459 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
5460 DemandBits |= ShlDemandBits;
5464 case llvm::Instruction::Trunc: {
5465 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5466 unsigned TruncBitWidth = TruncVT.getSizeInBits();
5467 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
5468 DemandBits |= TruncBits;
5477 uint32_t ActiveBits = DemandBits.getActiveBits();
5478 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5479 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5480 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5481 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5482 // followed by an AND.
5483 // TODO: Look into removing this restriction by fixing backends to either
5484 // return false for isLoadExtLegal for i1 or have them select this pattern to
5485 // a single instruction.
5487 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5488 // mask, since these are the only ands that will be removed by isel.
5489 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
5490 WidestAndBits != DemandBits)
5493 LLVMContext &Ctx = Load->getType()->getContext();
5494 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5495 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5497 // Reject cases that won't be matched as extloads.
5498 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5499 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5502 IRBuilder<> Builder(Load->getNextNode());
5503 auto *NewAnd = dyn_cast<Instruction>(
5504 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5506 // Replace all uses of load with new and (except for the use of load in the
5508 Load->replaceAllUsesWith(NewAnd);
5509 NewAnd->setOperand(0, Load);
5511 // Remove any and instructions that are now redundant.
5512 for (auto *And : AndsToMaybeRemove)
5513 // Check that the and mask is the same as the one we decided to put on the
5515 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5516 And->replaceAllUsesWith(NewAnd);
5517 if (&*CurInstIterator == And)
5518 CurInstIterator = std::next(And->getIterator());
5519 And->eraseFromParent();
5527 /// Check if V (an operand of a select instruction) is an expensive instruction
5528 /// that is only used once.
5529 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5530 auto *I = dyn_cast<Instruction>(V);
5531 // If it's safe to speculatively execute, then it should not have side
5532 // effects; therefore, it's safe to sink and possibly *not* execute.
5533 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5534 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5537 /// Returns true if a SelectInst should be turned into an explicit branch.
5538 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
5540 // FIXME: This should use the same heuristics as IfConversion to determine
5541 // whether a select is better represented as a branch. This requires that
5542 // branch probability metadata is preserved for the select, which is not the
5545 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5547 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5548 // comparison condition. If the compare has more than one use, there's
5549 // probably another cmov or setcc around, so it's not worth emitting a branch.
5550 if (!Cmp || !Cmp->hasOneUse())
5553 Value *CmpOp0 = Cmp->getOperand(0);
5554 Value *CmpOp1 = Cmp->getOperand(1);
5556 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
5557 // on a load from memory. But if the load is used more than once, do not
5558 // change the select to a branch because the load is probably needed
5559 // regardless of whether the branch is taken or not.
5560 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
5561 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
5564 // If either operand of the select is expensive and only needed on one side
5565 // of the select, we should form a branch.
5566 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5567 sinkSelectOperand(TTI, SI->getFalseValue()))
5574 /// If we have a SelectInst that will likely profit from branch prediction,
5575 /// turn it into a branch.
5576 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5577 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5579 // Can we convert the 'select' to CF ?
5580 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
5583 TargetLowering::SelectSupportKind SelectKind;
5585 SelectKind = TargetLowering::VectorMaskSelect;
5586 else if (SI->getType()->isVectorTy())
5587 SelectKind = TargetLowering::ScalarCondVectorVal;
5589 SelectKind = TargetLowering::ScalarValSelect;
5591 // Do we have efficient codegen support for this kind of 'selects' ?
5592 if (TLI->isSelectSupported(SelectKind)) {
5593 // We have efficient codegen support for the select instruction.
5594 // Check if it is profitable to keep this 'select'.
5595 if (!TLI->isPredictableSelectExpensive() ||
5596 !isFormingBranchFromSelectProfitable(TTI, SI))
5602 // Transform a sequence like this:
5604 // %cmp = cmp uge i32 %a, %b
5605 // %sel = select i1 %cmp, i32 %c, i32 %d
5609 // %cmp = cmp uge i32 %a, %b
5610 // br i1 %cmp, label %select.true, label %select.false
5612 // br label %select.end
5614 // br label %select.end
5616 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5618 // In addition, we may sink instructions that produce %c or %d from
5619 // the entry block into the destination(s) of the new branch.
5620 // If the true or false blocks do not contain a sunken instruction, that
5621 // block and its branch may be optimized away. In that case, one side of the
5622 // first branch will point directly to select.end, and the corresponding PHI
5623 // predecessor block will be the start block.
5625 // First, we split the block containing the select into 2 blocks.
5626 BasicBlock *StartBlock = SI->getParent();
5627 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
5628 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
5630 // Delete the unconditional branch that was just created by the split.
5631 StartBlock->getTerminator()->eraseFromParent();
5633 // These are the new basic blocks for the conditional branch.
5634 // At least one will become an actual new basic block.
5635 BasicBlock *TrueBlock = nullptr;
5636 BasicBlock *FalseBlock = nullptr;
5638 // Sink expensive instructions into the conditional blocks to avoid executing
5639 // them speculatively.
5640 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5641 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5642 EndBlock->getParent(), EndBlock);
5643 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5644 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5645 TrueInst->moveBefore(TrueBranch);
5647 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5648 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5649 EndBlock->getParent(), EndBlock);
5650 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5651 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5652 FalseInst->moveBefore(FalseBranch);
5655 // If there was nothing to sink, then arbitrarily choose the 'false' side
5656 // for a new input value to the PHI.
5657 if (TrueBlock == FalseBlock) {
5658 assert(TrueBlock == nullptr &&
5659 "Unexpected basic block transform while optimizing select");
5661 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5662 EndBlock->getParent(), EndBlock);
5663 BranchInst::Create(EndBlock, FalseBlock);
5666 // Insert the real conditional branch based on the original condition.
5667 // If we did not create a new block for one of the 'true' or 'false' paths
5668 // of the condition, it means that side of the branch goes to the end block
5669 // directly and the path originates from the start block from the point of
5670 // view of the new PHI.
5671 if (TrueBlock == nullptr) {
5672 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
5673 TrueBlock = StartBlock;
5674 } else if (FalseBlock == nullptr) {
5675 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
5676 FalseBlock = StartBlock;
5678 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
5681 // The select itself is replaced with a PHI Node.
5682 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5684 PN->addIncoming(SI->getTrueValue(), TrueBlock);
5685 PN->addIncoming(SI->getFalseValue(), FalseBlock);
5687 SI->replaceAllUsesWith(PN);
5688 SI->eraseFromParent();
5690 // Instruct OptimizeBlock to skip to the next block.
5691 CurInstIterator = StartBlock->end();
5692 ++NumSelectsExpanded;
5696 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
5697 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5699 for (unsigned i = 0; i < Mask.size(); ++i) {
5700 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5702 SplatElem = Mask[i];
5708 /// Some targets have expensive vector shifts if the lanes aren't all the same
5709 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5710 /// it's often worth sinking a shufflevector splat down to its use so that
5711 /// codegen can spot all lanes are identical.
5712 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
5713 BasicBlock *DefBB = SVI->getParent();
5715 // Only do this xform if variable vector shifts are particularly expensive.
5716 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5719 // We only expect better codegen by sinking a shuffle if we can recognise a
5721 if (!isBroadcastShuffle(SVI))
5724 // InsertedShuffles - Only insert a shuffle in each block once.
5725 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5727 bool MadeChange = false;
5728 for (User *U : SVI->users()) {
5729 Instruction *UI = cast<Instruction>(U);
5731 // Figure out which BB this ext is used in.
5732 BasicBlock *UserBB = UI->getParent();
5733 if (UserBB == DefBB) continue;
5735 // For now only apply this when the splat is used by a shift instruction.
5736 if (!UI->isShift()) continue;
5738 // Everything checks out, sink the shuffle if the user's block doesn't
5739 // already have a copy.
5740 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5742 if (!InsertedShuffle) {
5743 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5744 assert(InsertPt != UserBB->end());
5746 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5747 SVI->getOperand(2), "", &*InsertPt);
5750 UI->replaceUsesOfWith(SVI, InsertedShuffle);
5754 // If we removed all uses, nuke the shuffle.
5755 if (SVI->use_empty()) {
5756 SVI->eraseFromParent();
5763 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5767 Value *Cond = SI->getCondition();
5768 Type *OldType = Cond->getType();
5769 LLVMContext &Context = Cond->getContext();
5770 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5771 unsigned RegWidth = RegType.getSizeInBits();
5773 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5776 // If the register width is greater than the type width, expand the condition
5777 // of the switch instruction and each case constant to the width of the
5778 // register. By widening the type of the switch condition, subsequent
5779 // comparisons (for case comparisons) will not need to be extended to the
5780 // preferred register width, so we will potentially eliminate N-1 extends,
5781 // where N is the number of cases in the switch.
5782 auto *NewType = Type::getIntNTy(Context, RegWidth);
5784 // Zero-extend the switch condition and case constants unless the switch
5785 // condition is a function argument that is already being sign-extended.
5786 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5787 // everything instead.
5788 Instruction::CastOps ExtType = Instruction::ZExt;
5789 if (auto *Arg = dyn_cast<Argument>(Cond))
5790 if (Arg->hasSExtAttr())
5791 ExtType = Instruction::SExt;
5793 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5794 ExtInst->insertBefore(SI);
5795 SI->setCondition(ExtInst);
5796 for (SwitchInst::CaseIt Case : SI->cases()) {
5797 APInt NarrowConst = Case.getCaseValue()->getValue();
5798 APInt WideConst = (ExtType == Instruction::ZExt) ?
5799 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5800 Case.setValue(ConstantInt::get(Context, WideConst));
5807 /// \brief Helper class to promote a scalar operation to a vector one.
5808 /// This class is used to move downward extractelement transition.
5810 /// a = vector_op <2 x i32>
5811 /// b = extractelement <2 x i32> a, i32 0
5816 /// a = vector_op <2 x i32>
5817 /// c = vector_op a (equivalent to scalar_op on the related lane)
5818 /// * d = extractelement <2 x i32> c, i32 0
5820 /// Assuming both extractelement and store can be combine, we get rid of the
5822 class VectorPromoteHelper {
5823 /// DataLayout associated with the current module.
5824 const DataLayout &DL;
5826 /// Used to perform some checks on the legality of vector operations.
5827 const TargetLowering &TLI;
5829 /// Used to estimated the cost of the promoted chain.
5830 const TargetTransformInfo &TTI;
5832 /// The transition being moved downwards.
5833 Instruction *Transition;
5834 /// The sequence of instructions to be promoted.
5835 SmallVector<Instruction *, 4> InstsToBePromoted;
5836 /// Cost of combining a store and an extract.
5837 unsigned StoreExtractCombineCost;
5838 /// Instruction that will be combined with the transition.
5839 Instruction *CombineInst;
5841 /// \brief The instruction that represents the current end of the transition.
5842 /// Since we are faking the promotion until we reach the end of the chain
5843 /// of computation, we need a way to get the current end of the transition.
5844 Instruction *getEndOfTransition() const {
5845 if (InstsToBePromoted.empty())
5847 return InstsToBePromoted.back();
5850 /// \brief Return the index of the original value in the transition.
5851 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5852 /// c, is at index 0.
5853 unsigned getTransitionOriginalValueIdx() const {
5854 assert(isa<ExtractElementInst>(Transition) &&
5855 "Other kind of transitions are not supported yet");
5859 /// \brief Return the index of the index in the transition.
5860 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5862 unsigned getTransitionIdx() const {
5863 assert(isa<ExtractElementInst>(Transition) &&
5864 "Other kind of transitions are not supported yet");
5868 /// \brief Get the type of the transition.
5869 /// This is the type of the original value.
5870 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5871 /// transition is <2 x i32>.
5872 Type *getTransitionType() const {
5873 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5876 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5877 /// I.e., we have the following sequence:
5878 /// Def = Transition <ty1> a to <ty2>
5879 /// b = ToBePromoted <ty2> Def, ...
5881 /// b = ToBePromoted <ty1> a, ...
5882 /// Def = Transition <ty1> ToBePromoted to <ty2>
5883 void promoteImpl(Instruction *ToBePromoted);
5885 /// \brief Check whether or not it is profitable to promote all the
5886 /// instructions enqueued to be promoted.
5887 bool isProfitableToPromote() {
5888 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5889 unsigned Index = isa<ConstantInt>(ValIdx)
5890 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5892 Type *PromotedType = getTransitionType();
5894 StoreInst *ST = cast<StoreInst>(CombineInst);
5895 unsigned AS = ST->getPointerAddressSpace();
5896 unsigned Align = ST->getAlignment();
5897 // Check if this store is supported.
5898 if (!TLI.allowsMisalignedMemoryAccesses(
5899 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5901 // If this is not supported, there is no way we can combine
5902 // the extract with the store.
5906 // The scalar chain of computation has to pay for the transition
5907 // scalar to vector.
5908 // The vector chain has to account for the combining cost.
5909 uint64_t ScalarCost =
5910 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5911 uint64_t VectorCost = StoreExtractCombineCost;
5912 for (const auto &Inst : InstsToBePromoted) {
5913 // Compute the cost.
5914 // By construction, all instructions being promoted are arithmetic ones.
5915 // Moreover, one argument is a constant that can be viewed as a splat
5917 Value *Arg0 = Inst->getOperand(0);
5918 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5919 isa<ConstantFP>(Arg0);
5920 TargetTransformInfo::OperandValueKind Arg0OVK =
5921 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5922 : TargetTransformInfo::OK_AnyValue;
5923 TargetTransformInfo::OperandValueKind Arg1OVK =
5924 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5925 : TargetTransformInfo::OK_AnyValue;
5926 ScalarCost += TTI.getArithmeticInstrCost(
5927 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5928 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5931 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5932 << ScalarCost << "\nVector: " << VectorCost << '\n');
5933 return ScalarCost > VectorCost;
5936 /// \brief Generate a constant vector with \p Val with the same
5937 /// number of elements as the transition.
5938 /// \p UseSplat defines whether or not \p Val should be replicated
5939 /// across the whole vector.
5940 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5941 /// otherwise we generate a vector with as many undef as possible:
5942 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5943 /// used at the index of the extract.
5944 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5945 unsigned ExtractIdx = UINT_MAX;
5947 // If we cannot determine where the constant must be, we have to
5948 // use a splat constant.
5949 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5950 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5951 ExtractIdx = CstVal->getSExtValue();
5956 unsigned End = getTransitionType()->getVectorNumElements();
5958 return ConstantVector::getSplat(End, Val);
5960 SmallVector<Constant *, 4> ConstVec;
5961 UndefValue *UndefVal = UndefValue::get(Val->getType());
5962 for (unsigned Idx = 0; Idx != End; ++Idx) {
5963 if (Idx == ExtractIdx)
5964 ConstVec.push_back(Val);
5966 ConstVec.push_back(UndefVal);
5968 return ConstantVector::get(ConstVec);
5971 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5972 /// in \p Use can trigger undefined behavior.
5973 static bool canCauseUndefinedBehavior(const Instruction *Use,
5974 unsigned OperandIdx) {
5975 // This is not safe to introduce undef when the operand is on
5976 // the right hand side of a division-like instruction.
5977 if (OperandIdx != 1)
5979 switch (Use->getOpcode()) {
5982 case Instruction::SDiv:
5983 case Instruction::UDiv:
5984 case Instruction::SRem:
5985 case Instruction::URem:
5987 case Instruction::FDiv:
5988 case Instruction::FRem:
5989 return !Use->hasNoNaNs();
5991 llvm_unreachable(nullptr);
5995 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5996 const TargetTransformInfo &TTI, Instruction *Transition,
5997 unsigned CombineCost)
5998 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
5999 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
6000 assert(Transition && "Do not know how to promote null");
6003 /// \brief Check if we can promote \p ToBePromoted to \p Type.
6004 bool canPromote(const Instruction *ToBePromoted) const {
6005 // We could support CastInst too.
6006 return isa<BinaryOperator>(ToBePromoted);
6009 /// \brief Check if it is profitable to promote \p ToBePromoted
6010 /// by moving downward the transition through.
6011 bool shouldPromote(const Instruction *ToBePromoted) const {
6012 // Promote only if all the operands can be statically expanded.
6013 // Indeed, we do not want to introduce any new kind of transitions.
6014 for (const Use &U : ToBePromoted->operands()) {
6015 const Value *Val = U.get();
6016 if (Val == getEndOfTransition()) {
6017 // If the use is a division and the transition is on the rhs,
6018 // we cannot promote the operation, otherwise we may create a
6019 // division by zero.
6020 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6024 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6025 !isa<ConstantFP>(Val))
6028 // Check that the resulting operation is legal.
6029 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6032 return StressStoreExtract ||
6033 TLI.isOperationLegalOrCustom(
6034 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
6037 /// \brief Check whether or not \p Use can be combined
6038 /// with the transition.
6039 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6040 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6042 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
6043 void enqueueForPromotion(Instruction *ToBePromoted) {
6044 InstsToBePromoted.push_back(ToBePromoted);
6047 /// \brief Set the instruction that will be combined with the transition.
6048 void recordCombineInstruction(Instruction *ToBeCombined) {
6049 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6050 CombineInst = ToBeCombined;
6053 /// \brief Promote all the instructions enqueued for promotion if it is
6055 /// \return True if the promotion happened, false otherwise.
6057 // Check if there is something to promote.
6058 // Right now, if we do not have anything to combine with,
6059 // we assume the promotion is not profitable.
6060 if (InstsToBePromoted.empty() || !CombineInst)
6064 if (!StressStoreExtract && !isProfitableToPromote())
6068 for (auto &ToBePromoted : InstsToBePromoted)
6069 promoteImpl(ToBePromoted);
6070 InstsToBePromoted.clear();
6074 } // End of anonymous namespace.
6076 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6077 // At this point, we know that all the operands of ToBePromoted but Def
6078 // can be statically promoted.
6079 // For Def, we need to use its parameter in ToBePromoted:
6080 // b = ToBePromoted ty1 a
6081 // Def = Transition ty1 b to ty2
6082 // Move the transition down.
6083 // 1. Replace all uses of the promoted operation by the transition.
6084 // = ... b => = ... Def.
6085 assert(ToBePromoted->getType() == Transition->getType() &&
6086 "The type of the result of the transition does not match "
6088 ToBePromoted->replaceAllUsesWith(Transition);
6089 // 2. Update the type of the uses.
6090 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6091 Type *TransitionTy = getTransitionType();
6092 ToBePromoted->mutateType(TransitionTy);
6093 // 3. Update all the operands of the promoted operation with promoted
6095 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6096 for (Use &U : ToBePromoted->operands()) {
6097 Value *Val = U.get();
6098 Value *NewVal = nullptr;
6099 if (Val == Transition)
6100 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6101 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6102 isa<ConstantFP>(Val)) {
6103 // Use a splat constant if it is not safe to use undef.
6104 NewVal = getConstantVector(
6105 cast<Constant>(Val),
6106 isa<UndefValue>(Val) ||
6107 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6109 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6111 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6113 Transition->removeFromParent();
6114 Transition->insertAfter(ToBePromoted);
6115 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6118 /// Some targets can do store(extractelement) with one instruction.
6119 /// Try to push the extractelement towards the stores when the target
6120 /// has this feature and this is profitable.
6121 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
6122 unsigned CombineCost = UINT_MAX;
6123 if (DisableStoreExtract || !TLI ||
6124 (!StressStoreExtract &&
6125 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6126 Inst->getOperand(1), CombineCost)))
6129 // At this point we know that Inst is a vector to scalar transition.
6130 // Try to move it down the def-use chain, until:
6131 // - We can combine the transition with its single use
6132 // => we got rid of the transition.
6133 // - We escape the current basic block
6134 // => we would need to check that we are moving it at a cheaper place and
6135 // we do not do that for now.
6136 BasicBlock *Parent = Inst->getParent();
6137 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
6138 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
6139 // If the transition has more than one use, assume this is not going to be
6141 while (Inst->hasOneUse()) {
6142 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
6143 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
6145 if (ToBePromoted->getParent() != Parent) {
6146 DEBUG(dbgs() << "Instruction to promote is in a different block ("
6147 << ToBePromoted->getParent()->getName()
6148 << ") than the transition (" << Parent->getName() << ").\n");
6152 if (VPH.canCombine(ToBePromoted)) {
6153 DEBUG(dbgs() << "Assume " << *Inst << '\n'
6154 << "will be combined with: " << *ToBePromoted << '\n');
6155 VPH.recordCombineInstruction(ToBePromoted);
6156 bool Changed = VPH.promote();
6157 NumStoreExtractExposed += Changed;
6161 DEBUG(dbgs() << "Try promoting.\n");
6162 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6165 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
6167 VPH.enqueueForPromotion(ToBePromoted);
6168 Inst = ToBePromoted;
6173 bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
6174 // Bail out if we inserted the instruction to prevent optimizations from
6175 // stepping on each other's toes.
6176 if (InsertedInsts.count(I))
6179 if (PHINode *P = dyn_cast<PHINode>(I)) {
6180 // It is possible for very late stage optimizations (such as SimplifyCFG)
6181 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6182 // trivial PHI, go ahead and zap it here.
6183 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
6184 P->replaceAllUsesWith(V);
6185 P->eraseFromParent();
6192 if (CastInst *CI = dyn_cast<CastInst>(I)) {
6193 // If the source of the cast is a constant, then this should have
6194 // already been constant folded. The only reason NOT to constant fold
6195 // it is if something (e.g. LSR) was careful to place the constant
6196 // evaluation in a block other than then one that uses it (e.g. to hoist
6197 // the address of globals out of a loop). If this is the case, we don't
6198 // want to forward-subst the cast.
6199 if (isa<Constant>(CI->getOperand(0)))
6202 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
6205 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6206 /// Sink a zext or sext into its user blocks if the target type doesn't
6207 /// fit in one register
6209 TLI->getTypeAction(CI->getContext(),
6210 TLI->getValueType(*DL, CI->getType())) ==
6211 TargetLowering::TypeExpandInteger) {
6212 return SinkCast(CI);
6214 bool MadeChange = moveExtToFormExtLoad(I);
6215 return MadeChange | optimizeExtUses(I);
6221 if (CmpInst *CI = dyn_cast<CmpInst>(I))
6222 if (!TLI || !TLI->hasMultipleConditionRegisters())
6223 return OptimizeCmpExpression(CI);
6225 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6226 stripInvariantGroupMetadata(*LI);
6228 bool Modified = optimizeLoadExt(LI);
6229 unsigned AS = LI->getPointerAddressSpace();
6230 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6236 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6237 stripInvariantGroupMetadata(*SI);
6239 unsigned AS = SI->getPointerAddressSpace();
6240 return optimizeMemoryInst(I, SI->getOperand(1),
6241 SI->getOperand(0)->getType(), AS);
6246 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6248 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6249 BinOp->getOpcode() == Instruction::LShr)) {
6250 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6251 if (TLI && CI && TLI->hasExtractBitsInsn())
6252 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
6257 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
6258 if (GEPI->hasAllZeroIndices()) {
6259 /// The GEP operand must be a pointer, so must its result -> BitCast
6260 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6261 GEPI->getName(), GEPI);
6262 GEPI->replaceAllUsesWith(NC);
6263 GEPI->eraseFromParent();
6265 optimizeInst(NC, ModifiedDT);
6271 if (CallInst *CI = dyn_cast<CallInst>(I))
6272 return optimizeCallInst(CI, ModifiedDT);
6274 if (SelectInst *SI = dyn_cast<SelectInst>(I))
6275 return optimizeSelectInst(SI);
6277 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
6278 return optimizeShuffleVectorInst(SVI);
6280 if (auto *Switch = dyn_cast<SwitchInst>(I))
6281 return optimizeSwitchInst(Switch);
6283 if (isa<ExtractElementInst>(I))
6284 return optimizeExtractElementInst(I);
6289 /// Given an OR instruction, check to see if this is a bitreverse
6290 /// idiom. If so, insert the new intrinsic and return true.
6291 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6292 const TargetLowering &TLI) {
6293 if (!I.getType()->isIntegerTy() ||
6294 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6295 TLI.getValueType(DL, I.getType(), true)))
6298 SmallVector<Instruction*, 4> Insts;
6299 if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
6301 Instruction *LastInst = Insts.back();
6302 I.replaceAllUsesWith(LastInst);
6303 RecursivelyDeleteTriviallyDeadInstructions(&I);
6307 // In this pass we look for GEP and cast instructions that are used
6308 // across basic blocks and rewrite them to improve basic-block-at-a-time
6310 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
6312 bool MadeChange = false;
6314 CurInstIterator = BB.begin();
6315 while (CurInstIterator != BB.end()) {
6316 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6321 bool MadeBitReverse = true;
6322 while (TLI && MadeBitReverse) {
6323 MadeBitReverse = false;
6324 for (auto &I : reverse(BB)) {
6325 if (makeBitReverse(I, *DL, *TLI)) {
6326 MadeBitReverse = MadeChange = true;
6331 MadeChange |= dupRetToEnableTailCallOpts(&BB);
6336 // llvm.dbg.value is far away from the value then iSel may not be able
6337 // handle it properly. iSel will drop llvm.dbg.value if it can not
6338 // find a node corresponding to the value.
6339 bool CodeGenPrepare::placeDbgValues(Function &F) {
6340 bool MadeChange = false;
6341 for (BasicBlock &BB : F) {
6342 Instruction *PrevNonDbgInst = nullptr;
6343 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
6344 Instruction *Insn = &*BI++;
6345 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
6346 // Leave dbg.values that refer to an alloca alone. These
6347 // instrinsics describe the address of a variable (= the alloca)
6348 // being taken. They should not be moved next to the alloca
6349 // (and to the beginning of the scope), but rather stay close to
6350 // where said address is used.
6351 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
6352 PrevNonDbgInst = Insn;
6356 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6357 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
6358 // If VI is a phi in a block with an EHPad terminator, we can't insert
6360 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6362 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6363 DVI->removeFromParent();
6364 if (isa<PHINode>(VI))
6365 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6367 DVI->insertAfter(VI);
6376 // If there is a sequence that branches based on comparing a single bit
6377 // against zero that can be combined into a single instruction, and the
6378 // target supports folding these into a single instruction, sink the
6379 // mask and compare into the branch uses. Do this before OptimizeBlock ->
6380 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
6382 bool CodeGenPrepare::sinkAndCmp(Function &F) {
6383 if (!EnableAndCmpSinking)
6385 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
6387 bool MadeChange = false;
6388 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
6389 BasicBlock *BB = &*I++;
6391 // Does this BB end with the following?
6392 // %andVal = and %val, #single-bit-set
6393 // %icmpVal = icmp %andResult, 0
6394 // br i1 %cmpVal label %dest1, label %dest2"
6395 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
6396 if (!Brcc || !Brcc->isConditional())
6398 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
6399 if (!Cmp || Cmp->getParent() != BB)
6401 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
6402 if (!Zero || !Zero->isZero())
6404 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
6405 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
6407 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
6408 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
6410 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
6412 // Push the "and; icmp" for any users that are conditional branches.
6413 // Since there can only be one branch use per BB, we don't need to keep
6414 // track of which BBs we insert into.
6415 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
6419 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
6421 if (!BrccUser || !BrccUser->isConditional())
6423 BasicBlock *UserBB = BrccUser->getParent();
6424 if (UserBB == BB) continue;
6425 DEBUG(dbgs() << "found Brcc use\n");
6427 // Sink the "and; icmp" to use.
6429 BinaryOperator *NewAnd =
6430 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
6433 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
6437 DEBUG(BrccUser->getParent()->dump());
6443 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
6444 /// success, or returns false if no or invalid metadata was found.
6445 static bool extractBranchMetadata(BranchInst *BI,
6446 uint64_t &ProbTrue, uint64_t &ProbFalse) {
6447 assert(BI->isConditional() &&
6448 "Looking for probabilities on unconditional branch?");
6449 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
6450 if (!ProfileData || ProfileData->getNumOperands() != 3)
6453 const auto *CITrue =
6454 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
6455 const auto *CIFalse =
6456 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
6457 if (!CITrue || !CIFalse)
6460 ProbTrue = CITrue->getValue().getZExtValue();
6461 ProbFalse = CIFalse->getValue().getZExtValue();
6466 /// \brief Scale down both weights to fit into uint32_t.
6467 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6468 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6469 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
6470 NewTrue = NewTrue / Scale;
6471 NewFalse = NewFalse / Scale;
6474 /// \brief Some targets prefer to split a conditional branch like:
6476 /// %0 = icmp ne i32 %a, 0
6477 /// %1 = icmp ne i32 %b, 0
6478 /// %or.cond = or i1 %0, %1
6479 /// br i1 %or.cond, label %TrueBB, label %FalseBB
6481 /// into multiple branch instructions like:
6484 /// %0 = icmp ne i32 %a, 0
6485 /// br i1 %0, label %TrueBB, label %bb2
6487 /// %1 = icmp ne i32 %b, 0
6488 /// br i1 %1, label %TrueBB, label %FalseBB
6490 /// This usually allows instruction selection to do even further optimizations
6491 /// and combine the compare with the branch instruction. Currently this is
6492 /// applied for targets which have "cheap" jump instructions.
6494 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6496 bool CodeGenPrepare::splitBranchCondition(Function &F) {
6497 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
6500 bool MadeChange = false;
6501 for (auto &BB : F) {
6502 // Does this BB end with the following?
6503 // %cond1 = icmp|fcmp|binary instruction ...
6504 // %cond2 = icmp|fcmp|binary instruction ...
6505 // %cond.or = or|and i1 %cond1, cond2
6506 // br i1 %cond.or label %dest1, label %dest2"
6507 BinaryOperator *LogicOp;
6508 BasicBlock *TBB, *FBB;
6509 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6512 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6513 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6517 Value *Cond1, *Cond2;
6518 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6519 m_OneUse(m_Value(Cond2)))))
6520 Opc = Instruction::And;
6521 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6522 m_OneUse(m_Value(Cond2)))))
6523 Opc = Instruction::Or;
6527 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6528 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6531 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6534 auto *InsertBefore = std::next(Function::iterator(BB))
6535 .getNodePtrUnchecked();
6536 auto TmpBB = BasicBlock::Create(BB.getContext(),
6537 BB.getName() + ".cond.split",
6538 BB.getParent(), InsertBefore);
6540 // Update original basic block by using the first condition directly by the
6541 // branch instruction and removing the no longer needed and/or instruction.
6542 Br1->setCondition(Cond1);
6543 LogicOp->eraseFromParent();
6545 // Depending on the conditon we have to either replace the true or the false
6546 // successor of the original branch instruction.
6547 if (Opc == Instruction::And)
6548 Br1->setSuccessor(0, TmpBB);
6550 Br1->setSuccessor(1, TmpBB);
6552 // Fill in the new basic block.
6553 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6554 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6555 I->removeFromParent();
6556 I->insertBefore(Br2);
6559 // Update PHI nodes in both successors. The original BB needs to be
6560 // replaced in one succesor's PHI nodes, because the branch comes now from
6561 // the newly generated BB (NewBB). In the other successor we need to add one
6562 // incoming edge to the PHI nodes, because both branch instructions target
6563 // now the same successor. Depending on the original branch condition
6564 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6565 // we perfrom the correct update for the PHI nodes.
6566 // This doesn't change the successor order of the just created branch
6567 // instruction (or any other instruction).
6568 if (Opc == Instruction::Or)
6569 std::swap(TBB, FBB);
6571 // Replace the old BB with the new BB.
6572 for (auto &I : *TBB) {
6573 PHINode *PN = dyn_cast<PHINode>(&I);
6577 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6578 PN->setIncomingBlock(i, TmpBB);
6581 // Add another incoming edge form the new BB.
6582 for (auto &I : *FBB) {
6583 PHINode *PN = dyn_cast<PHINode>(&I);
6586 auto *Val = PN->getIncomingValueForBlock(&BB);
6587 PN->addIncoming(Val, TmpBB);
6590 // Update the branch weights (from SelectionDAGBuilder::
6591 // FindMergedConditions).
6592 if (Opc == Instruction::Or) {
6593 // Codegen X | Y as:
6602 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6603 // The requirement is that
6604 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6605 // = TrueProb for orignal BB.
6606 // Assuming the orignal weights are A and B, one choice is to set BB1's
6607 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6609 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6610 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6611 // TmpBB, but the math is more complicated.
6612 uint64_t TrueWeight, FalseWeight;
6613 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
6614 uint64_t NewTrueWeight = TrueWeight;
6615 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6616 scaleWeights(NewTrueWeight, NewFalseWeight);
6617 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6618 .createBranchWeights(TrueWeight, FalseWeight));
6620 NewTrueWeight = TrueWeight;
6621 NewFalseWeight = 2 * FalseWeight;
6622 scaleWeights(NewTrueWeight, NewFalseWeight);
6623 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6624 .createBranchWeights(TrueWeight, FalseWeight));
6627 // Codegen X & Y as:
6635 // This requires creation of TmpBB after CurBB.
6637 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6638 // The requirement is that
6639 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6640 // = FalseProb for orignal BB.
6641 // Assuming the orignal weights are A and B, one choice is to set BB1's
6642 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6644 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6645 uint64_t TrueWeight, FalseWeight;
6646 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
6647 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6648 uint64_t NewFalseWeight = FalseWeight;
6649 scaleWeights(NewTrueWeight, NewFalseWeight);
6650 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6651 .createBranchWeights(TrueWeight, FalseWeight));
6653 NewTrueWeight = 2 * TrueWeight;
6654 NewFalseWeight = FalseWeight;
6655 scaleWeights(NewTrueWeight, NewFalseWeight);
6656 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6657 .createBranchWeights(TrueWeight, FalseWeight));
6661 // Note: No point in getting fancy here, since the DT info is never
6662 // available to CodeGenPrepare.
6667 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6673 void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
6674 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
6675 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());