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/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GetElementPtrTypeIterator.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/IR/ValueMap.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetLibraryInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/BuildLibCalls.h"
44 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
45 #include "llvm/Transforms/Utils/Local.h"
47 using namespace llvm::PatternMatch;
49 #define DEBUG_TYPE "codegenprepare"
51 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
52 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
53 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
54 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
56 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
58 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
59 "computations were sunk");
60 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
61 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
62 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
63 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
64 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
65 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
67 static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
71 static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
75 static cl::opt<bool> AddrSinkUsingGEPs(
76 "addr-sink-using-gep", cl::Hidden, cl::init(false),
77 cl::desc("Address sinking in CGP using GEPs."));
79 static cl::opt<bool> EnableAndCmpSinking(
80 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
81 cl::desc("Enable sinkinig and/cmp into branches."));
84 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
85 typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
87 class CodeGenPrepare : public FunctionPass {
88 /// TLI - Keep a pointer of a TargetLowering to consult for determining
89 /// transformation profitability.
90 const TargetMachine *TM;
91 const TargetLowering *TLI;
92 const TargetLibraryInfo *TLInfo;
95 /// CurInstIterator - As we scan instructions optimizing them, this is the
96 /// next instruction to optimize. Xforms that can invalidate this should
98 BasicBlock::iterator CurInstIterator;
100 /// Keeps track of non-local addresses that have been sunk into a block.
101 /// This allows us to avoid inserting duplicate code for blocks with
102 /// multiple load/stores of the same address.
103 ValueMap<Value*, Value*> SunkAddrs;
105 /// Keeps track of all truncates inserted for the current function.
106 SetOfInstrs InsertedTruncsSet;
107 /// Keeps track of the type of the related instruction before their
108 /// promotion for the current function.
109 InstrToOrigTy PromotedInsts;
111 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
115 /// OptSize - True if optimizing for size.
119 static char ID; // Pass identification, replacement for typeid
120 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
121 : FunctionPass(ID), TM(TM), TLI(nullptr) {
122 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
124 bool runOnFunction(Function &F) override;
126 const char *getPassName() const override { return "CodeGen Prepare"; }
128 void getAnalysisUsage(AnalysisUsage &AU) const override {
129 AU.addPreserved<DominatorTreeWrapperPass>();
130 AU.addRequired<TargetLibraryInfo>();
134 bool EliminateFallThrough(Function &F);
135 bool EliminateMostlyEmptyBlocks(Function &F);
136 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
137 void EliminateMostlyEmptyBlock(BasicBlock *BB);
138 bool OptimizeBlock(BasicBlock &BB);
139 bool OptimizeInst(Instruction *I);
140 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
141 bool OptimizeInlineAsmInst(CallInst *CS);
142 bool OptimizeCallInst(CallInst *CI);
143 bool MoveExtToFormExtLoad(Instruction *I);
144 bool OptimizeExtUses(Instruction *I);
145 bool OptimizeSelectInst(SelectInst *SI);
146 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
147 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
148 bool PlaceDbgValues(Function &F);
149 bool sinkAndCmp(Function &F);
153 char CodeGenPrepare::ID = 0;
154 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
155 "Optimize for code generation", false, false)
157 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
158 return new CodeGenPrepare(TM);
161 bool CodeGenPrepare::runOnFunction(Function &F) {
162 if (skipOptnoneFunction(F))
165 bool EverMadeChange = false;
166 // Clear per function information.
167 InsertedTruncsSet.clear();
168 PromotedInsts.clear();
172 TLI = TM->getSubtargetImpl()->getTargetLowering();
173 TLInfo = &getAnalysis<TargetLibraryInfo>();
174 DominatorTreeWrapperPass *DTWP =
175 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
176 DT = DTWP ? &DTWP->getDomTree() : nullptr;
177 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
178 Attribute::OptimizeForSize);
180 /// This optimization identifies DIV instructions that can be
181 /// profitably bypassed and carried out with a shorter, faster divide.
182 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
183 const DenseMap<unsigned int, unsigned int> &BypassWidths =
184 TLI->getBypassSlowDivWidths();
185 for (Function::iterator I = F.begin(); I != F.end(); I++)
186 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
189 // Eliminate blocks that contain only PHI nodes and an
190 // unconditional branch.
191 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
193 // llvm.dbg.value is far away from the value then iSel may not be able
194 // handle it properly. iSel will drop llvm.dbg.value if it can not
195 // find a node corresponding to the value.
196 EverMadeChange |= PlaceDbgValues(F);
198 // If there is a mask, compare against zero, and branch that can be combined
199 // into a single target instruction, push the mask and compare into branch
200 // users. Do this before OptimizeBlock -> OptimizeInst ->
201 // OptimizeCmpExpression, which perturbs the pattern being searched for.
202 if (!DisableBranchOpts)
203 EverMadeChange |= sinkAndCmp(F);
205 bool MadeChange = true;
208 for (Function::iterator I = F.begin(); I != F.end(); ) {
209 BasicBlock *BB = I++;
210 MadeChange |= OptimizeBlock(*BB);
212 EverMadeChange |= MadeChange;
217 if (!DisableBranchOpts) {
219 SmallPtrSet<BasicBlock*, 8> WorkList;
220 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
221 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
222 MadeChange |= ConstantFoldTerminator(BB, true);
223 if (!MadeChange) continue;
225 for (SmallVectorImpl<BasicBlock*>::iterator
226 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
227 if (pred_begin(*II) == pred_end(*II))
228 WorkList.insert(*II);
231 // Delete the dead blocks and any of their dead successors.
232 MadeChange |= !WorkList.empty();
233 while (!WorkList.empty()) {
234 BasicBlock *BB = *WorkList.begin();
236 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
240 for (SmallVectorImpl<BasicBlock*>::iterator
241 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
242 if (pred_begin(*II) == pred_end(*II))
243 WorkList.insert(*II);
246 // Merge pairs of basic blocks with unconditional branches, connected by
248 if (EverMadeChange || MadeChange)
249 MadeChange |= EliminateFallThrough(F);
253 EverMadeChange |= MadeChange;
256 if (ModifiedDT && DT)
259 return EverMadeChange;
262 /// EliminateFallThrough - Merge basic blocks which are connected
263 /// by a single edge, where one of the basic blocks has a single successor
264 /// pointing to the other basic block, which has a single predecessor.
265 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
266 bool Changed = false;
267 // Scan all of the blocks in the function, except for the entry block.
268 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
269 BasicBlock *BB = I++;
270 // If the destination block has a single pred, then this is a trivial
271 // edge, just collapse it.
272 BasicBlock *SinglePred = BB->getSinglePredecessor();
274 // Don't merge if BB's address is taken.
275 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
277 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
278 if (Term && !Term->isConditional()) {
280 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
281 // Remember if SinglePred was the entry block of the function.
282 // If so, we will need to move BB back to the entry position.
283 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
284 MergeBasicBlockIntoOnlyPred(BB, this);
286 if (isEntry && BB != &BB->getParent()->getEntryBlock())
287 BB->moveBefore(&BB->getParent()->getEntryBlock());
289 // We have erased a block. Update the iterator.
296 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
297 /// debug info directives, and an unconditional branch. Passes before isel
298 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
299 /// isel. Start by eliminating these blocks so we can split them the way we
301 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
302 bool MadeChange = false;
303 // Note that this intentionally skips the entry block.
304 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
305 BasicBlock *BB = I++;
307 // If this block doesn't end with an uncond branch, ignore it.
308 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
309 if (!BI || !BI->isUnconditional())
312 // If the instruction before the branch (skipping debug info) isn't a phi
313 // node, then other stuff is happening here.
314 BasicBlock::iterator BBI = BI;
315 if (BBI != BB->begin()) {
317 while (isa<DbgInfoIntrinsic>(BBI)) {
318 if (BBI == BB->begin())
322 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
326 // Do not break infinite loops.
327 BasicBlock *DestBB = BI->getSuccessor(0);
331 if (!CanMergeBlocks(BB, DestBB))
334 EliminateMostlyEmptyBlock(BB);
340 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
341 /// single uncond branch between them, and BB contains no other non-phi
343 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
344 const BasicBlock *DestBB) const {
345 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
346 // the successor. If there are more complex condition (e.g. preheaders),
347 // don't mess around with them.
348 BasicBlock::const_iterator BBI = BB->begin();
349 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
350 for (const User *U : PN->users()) {
351 const Instruction *UI = cast<Instruction>(U);
352 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
354 // If User is inside DestBB block and it is a PHINode then check
355 // incoming value. If incoming value is not from BB then this is
356 // a complex condition (e.g. preheaders) we want to avoid here.
357 if (UI->getParent() == DestBB) {
358 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
359 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
360 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
361 if (Insn && Insn->getParent() == BB &&
362 Insn->getParent() != UPN->getIncomingBlock(I))
369 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
370 // and DestBB may have conflicting incoming values for the block. If so, we
371 // can't merge the block.
372 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
373 if (!DestBBPN) return true; // no conflict.
375 // Collect the preds of BB.
376 SmallPtrSet<const BasicBlock*, 16> BBPreds;
377 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
378 // It is faster to get preds from a PHI than with pred_iterator.
379 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
380 BBPreds.insert(BBPN->getIncomingBlock(i));
382 BBPreds.insert(pred_begin(BB), pred_end(BB));
385 // Walk the preds of DestBB.
386 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
387 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
388 if (BBPreds.count(Pred)) { // Common predecessor?
389 BBI = DestBB->begin();
390 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
391 const Value *V1 = PN->getIncomingValueForBlock(Pred);
392 const Value *V2 = PN->getIncomingValueForBlock(BB);
394 // If V2 is a phi node in BB, look up what the mapped value will be.
395 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
396 if (V2PN->getParent() == BB)
397 V2 = V2PN->getIncomingValueForBlock(Pred);
399 // If there is a conflict, bail out.
400 if (V1 != V2) return false;
409 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
410 /// an unconditional branch in it.
411 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
412 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
413 BasicBlock *DestBB = BI->getSuccessor(0);
415 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
417 // If the destination block has a single pred, then this is a trivial edge,
419 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
420 if (SinglePred != DestBB) {
421 // Remember if SinglePred was the entry block of the function. If so, we
422 // will need to move BB back to the entry position.
423 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
424 MergeBasicBlockIntoOnlyPred(DestBB, this);
426 if (isEntry && BB != &BB->getParent()->getEntryBlock())
427 BB->moveBefore(&BB->getParent()->getEntryBlock());
429 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
434 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
435 // to handle the new incoming edges it is about to have.
437 for (BasicBlock::iterator BBI = DestBB->begin();
438 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
439 // Remove the incoming value for BB, and remember it.
440 Value *InVal = PN->removeIncomingValue(BB, false);
442 // Two options: either the InVal is a phi node defined in BB or it is some
443 // value that dominates BB.
444 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
445 if (InValPhi && InValPhi->getParent() == BB) {
446 // Add all of the input values of the input PHI as inputs of this phi.
447 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
448 PN->addIncoming(InValPhi->getIncomingValue(i),
449 InValPhi->getIncomingBlock(i));
451 // Otherwise, add one instance of the dominating value for each edge that
452 // we will be adding.
453 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
454 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
455 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
457 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
458 PN->addIncoming(InVal, *PI);
463 // The PHIs are now updated, change everything that refers to BB to use
464 // DestBB and remove BB.
465 BB->replaceAllUsesWith(DestBB);
466 if (DT && !ModifiedDT) {
467 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
468 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
469 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
470 DT->changeImmediateDominator(DestBB, NewIDom);
473 BB->eraseFromParent();
476 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
479 /// SinkCast - Sink the specified cast instruction into its user blocks
480 static bool SinkCast(CastInst *CI) {
481 BasicBlock *DefBB = CI->getParent();
483 /// InsertedCasts - Only insert a cast in each block once.
484 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
486 bool MadeChange = false;
487 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
489 Use &TheUse = UI.getUse();
490 Instruction *User = cast<Instruction>(*UI);
492 // Figure out which BB this cast is used in. For PHI's this is the
493 // appropriate predecessor block.
494 BasicBlock *UserBB = User->getParent();
495 if (PHINode *PN = dyn_cast<PHINode>(User)) {
496 UserBB = PN->getIncomingBlock(TheUse);
499 // Preincrement use iterator so we don't invalidate it.
502 // If this user is in the same block as the cast, don't change the cast.
503 if (UserBB == DefBB) continue;
505 // If we have already inserted a cast into this block, use it.
506 CastInst *&InsertedCast = InsertedCasts[UserBB];
509 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
511 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
516 // Replace a use of the cast with a use of the new cast.
517 TheUse = InsertedCast;
521 // If we removed all uses, nuke the cast.
522 if (CI->use_empty()) {
523 CI->eraseFromParent();
530 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
531 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
532 /// sink it into user blocks to reduce the number of virtual
533 /// registers that must be created and coalesced.
535 /// Return true if any changes are made.
537 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
538 // If this is a noop copy,
539 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
540 EVT DstVT = TLI.getValueType(CI->getType());
542 // This is an fp<->int conversion?
543 if (SrcVT.isInteger() != DstVT.isInteger())
546 // If this is an extension, it will be a zero or sign extension, which
548 if (SrcVT.bitsLT(DstVT)) return false;
550 // If these values will be promoted, find out what they will be promoted
551 // to. This helps us consider truncates on PPC as noop copies when they
553 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
554 TargetLowering::TypePromoteInteger)
555 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
556 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
557 TargetLowering::TypePromoteInteger)
558 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
560 // If, after promotion, these are the same types, this is a noop copy.
567 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
568 /// the number of virtual registers that must be created and coalesced. This is
569 /// a clear win except on targets with multiple condition code registers
570 /// (PowerPC), where it might lose; some adjustment may be wanted there.
572 /// Return true if any changes are made.
573 static bool OptimizeCmpExpression(CmpInst *CI) {
574 BasicBlock *DefBB = CI->getParent();
576 /// InsertedCmp - Only insert a cmp in each block once.
577 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
579 bool MadeChange = false;
580 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
582 Use &TheUse = UI.getUse();
583 Instruction *User = cast<Instruction>(*UI);
585 // Preincrement use iterator so we don't invalidate it.
588 // Don't bother for PHI nodes.
589 if (isa<PHINode>(User))
592 // Figure out which BB this cmp is used in.
593 BasicBlock *UserBB = User->getParent();
595 // If this user is in the same block as the cmp, don't change the cmp.
596 if (UserBB == DefBB) continue;
598 // If we have already inserted a cmp into this block, use it.
599 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
602 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
604 CmpInst::Create(CI->getOpcode(),
605 CI->getPredicate(), CI->getOperand(0),
606 CI->getOperand(1), "", InsertPt);
610 // Replace a use of the cmp with a use of the new cmp.
611 TheUse = InsertedCmp;
615 // If we removed all uses, nuke the cmp.
617 CI->eraseFromParent();
622 /// isExtractBitsCandidateUse - Check if the candidates could
623 /// be combined with shift instruction, which includes:
624 /// 1. Truncate instruction
625 /// 2. And instruction and the imm is a mask of the low bits:
626 /// imm & (imm+1) == 0
627 static bool isExtractBitsCandidateUse(Instruction *User) {
628 if (!isa<TruncInst>(User)) {
629 if (User->getOpcode() != Instruction::And ||
630 !isa<ConstantInt>(User->getOperand(1)))
633 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
635 if ((Cimm & (Cimm + 1)).getBoolValue())
641 /// SinkShiftAndTruncate - sink both shift and truncate instruction
642 /// to the use of truncate's BB.
644 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
645 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
646 const TargetLowering &TLI) {
647 BasicBlock *UserBB = User->getParent();
648 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
649 TruncInst *TruncI = dyn_cast<TruncInst>(User);
650 bool MadeChange = false;
652 for (Value::user_iterator TruncUI = TruncI->user_begin(),
653 TruncE = TruncI->user_end();
654 TruncUI != TruncE;) {
656 Use &TruncTheUse = TruncUI.getUse();
657 Instruction *TruncUser = cast<Instruction>(*TruncUI);
658 // Preincrement use iterator so we don't invalidate it.
662 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
666 // If the use is actually a legal node, there will not be an
667 // implicit truncate.
668 // FIXME: always querying the result type is just an
669 // approximation; some nodes' legality is determined by the
670 // operand or other means. There's no good way to find out though.
671 if (TLI.isOperationLegalOrCustom(ISDOpcode,
672 EVT::getEVT(TruncUser->getType(), true)))
675 // Don't bother for PHI nodes.
676 if (isa<PHINode>(TruncUser))
679 BasicBlock *TruncUserBB = TruncUser->getParent();
681 if (UserBB == TruncUserBB)
684 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
685 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
687 if (!InsertedShift && !InsertedTrunc) {
688 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
690 if (ShiftI->getOpcode() == Instruction::AShr)
692 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
695 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
698 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
701 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
702 TruncI->getType(), "", TruncInsertPt);
706 TruncTheUse = InsertedTrunc;
712 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
713 /// the uses could potentially be combined with this shift instruction and
714 /// generate BitExtract instruction. It will only be applied if the architecture
715 /// supports BitExtract instruction. Here is an example:
717 /// %x.extract.shift = lshr i64 %arg1, 32
719 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
723 /// %x.extract.shift.1 = lshr i64 %arg1, 32
724 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
726 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
728 /// Return true if any changes are made.
729 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
730 const TargetLowering &TLI) {
731 BasicBlock *DefBB = ShiftI->getParent();
733 /// Only insert instructions in each block once.
734 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
736 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
738 bool MadeChange = false;
739 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
741 Use &TheUse = UI.getUse();
742 Instruction *User = cast<Instruction>(*UI);
743 // Preincrement use iterator so we don't invalidate it.
746 // Don't bother for PHI nodes.
747 if (isa<PHINode>(User))
750 if (!isExtractBitsCandidateUse(User))
753 BasicBlock *UserBB = User->getParent();
755 if (UserBB == DefBB) {
756 // If the shift and truncate instruction are in the same BB. The use of
757 // the truncate(TruncUse) may still introduce another truncate if not
758 // legal. In this case, we would like to sink both shift and truncate
759 // instruction to the BB of TruncUse.
762 // i64 shift.result = lshr i64 opnd, imm
763 // trunc.result = trunc shift.result to i16
766 // ----> We will have an implicit truncate here if the architecture does
767 // not have i16 compare.
768 // cmp i16 trunc.result, opnd2
770 if (isa<TruncInst>(User) && shiftIsLegal
771 // If the type of the truncate is legal, no trucate will be
772 // introduced in other basic blocks.
773 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
775 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
779 // If we have already inserted a shift into this block, use it.
780 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
782 if (!InsertedShift) {
783 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
785 if (ShiftI->getOpcode() == Instruction::AShr)
787 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
790 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
795 // Replace a use of the shift with a use of the new shift.
796 TheUse = InsertedShift;
799 // If we removed all uses, nuke the shift.
800 if (ShiftI->use_empty())
801 ShiftI->eraseFromParent();
807 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
809 void replaceCall(Value *With) override {
810 CI->replaceAllUsesWith(With);
811 CI->eraseFromParent();
813 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
814 if (ConstantInt *SizeCI =
815 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
816 return SizeCI->isAllOnesValue();
820 } // end anonymous namespace
822 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
823 BasicBlock *BB = CI->getParent();
825 // Lower inline assembly if we can.
826 // If we found an inline asm expession, and if the target knows how to
827 // lower it to normal LLVM code, do so now.
828 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
829 if (TLI->ExpandInlineAsm(CI)) {
830 // Avoid invalidating the iterator.
831 CurInstIterator = BB->begin();
832 // Avoid processing instructions out of order, which could cause
833 // reuse before a value is defined.
837 // Sink address computing for memory operands into the block.
838 if (OptimizeInlineAsmInst(CI))
842 // Lower all uses of llvm.objectsize.*
843 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
844 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
845 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
846 Type *ReturnTy = CI->getType();
847 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
849 // Substituting this can cause recursive simplifications, which can
850 // invalidate our iterator. Use a WeakVH to hold onto it in case this
852 WeakVH IterHandle(CurInstIterator);
854 replaceAndRecursivelySimplify(CI, RetVal,
855 TLI ? TLI->getDataLayout() : nullptr,
856 TLInfo, ModifiedDT ? nullptr : DT);
858 // If the iterator instruction was recursively deleted, start over at the
859 // start of the block.
860 if (IterHandle != CurInstIterator) {
861 CurInstIterator = BB->begin();
868 SmallVector<Value*, 2> PtrOps;
870 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
871 while (!PtrOps.empty())
872 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
876 // From here on out we're working with named functions.
877 if (!CI->getCalledFunction()) return false;
879 // We'll need DataLayout from here on out.
880 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
881 if (!TD) return false;
883 // Lower all default uses of _chk calls. This is very similar
884 // to what InstCombineCalls does, but here we are only lowering calls
885 // that have the default "don't know" as the objectsize. Anything else
886 // should be left alone.
887 CodeGenPrepareFortifiedLibCalls Simplifier;
888 return Simplifier.fold(CI, TD, TLInfo);
891 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
892 /// instructions to the predecessor to enable tail call optimizations. The
893 /// case it is currently looking for is:
896 /// %tmp0 = tail call i32 @f0()
899 /// %tmp1 = tail call i32 @f1()
902 /// %tmp2 = tail call i32 @f2()
905 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
913 /// %tmp0 = tail call i32 @f0()
916 /// %tmp1 = tail call i32 @f1()
919 /// %tmp2 = tail call i32 @f2()
922 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
926 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
930 PHINode *PN = nullptr;
931 BitCastInst *BCI = nullptr;
932 Value *V = RI->getReturnValue();
934 BCI = dyn_cast<BitCastInst>(V);
936 V = BCI->getOperand(0);
938 PN = dyn_cast<PHINode>(V);
943 if (PN && PN->getParent() != BB)
946 // It's not safe to eliminate the sign / zero extension of the return value.
947 // See llvm::isInTailCallPosition().
948 const Function *F = BB->getParent();
949 AttributeSet CallerAttrs = F->getAttributes();
950 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
951 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
954 // Make sure there are no instructions between the PHI and return, or that the
955 // return is the first instruction in the block.
957 BasicBlock::iterator BI = BB->begin();
958 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
960 // Also skip over the bitcast.
965 BasicBlock::iterator BI = BB->begin();
966 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
971 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
973 SmallVector<CallInst*, 4> TailCalls;
975 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
976 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
977 // Make sure the phi value is indeed produced by the tail call.
978 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
979 TLI->mayBeEmittedAsTailCall(CI))
980 TailCalls.push_back(CI);
983 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
984 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
985 if (!VisitedBBs.insert(*PI))
988 BasicBlock::InstListType &InstList = (*PI)->getInstList();
989 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
990 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
991 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
995 CallInst *CI = dyn_cast<CallInst>(&*RI);
996 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
997 TailCalls.push_back(CI);
1001 bool Changed = false;
1002 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1003 CallInst *CI = TailCalls[i];
1006 // Conservatively require the attributes of the call to match those of the
1007 // return. Ignore noalias because it doesn't affect the call sequence.
1008 AttributeSet CalleeAttrs = CS.getAttributes();
1009 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1010 removeAttribute(Attribute::NoAlias) !=
1011 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1012 removeAttribute(Attribute::NoAlias))
1015 // Make sure the call instruction is followed by an unconditional branch to
1016 // the return block.
1017 BasicBlock *CallBB = CI->getParent();
1018 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1019 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1022 // Duplicate the return into CallBB.
1023 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1024 ModifiedDT = Changed = true;
1028 // If we eliminated all predecessors of the block, delete the block now.
1029 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1030 BB->eraseFromParent();
1035 //===----------------------------------------------------------------------===//
1036 // Memory Optimization
1037 //===----------------------------------------------------------------------===//
1041 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1042 /// which holds actual Value*'s for register values.
1043 struct ExtAddrMode : public TargetLowering::AddrMode {
1046 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1047 void print(raw_ostream &OS) const;
1050 bool operator==(const ExtAddrMode& O) const {
1051 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1052 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1053 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1058 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1064 void ExtAddrMode::print(raw_ostream &OS) const {
1065 bool NeedPlus = false;
1068 OS << (NeedPlus ? " + " : "")
1070 BaseGV->printAsOperand(OS, /*PrintType=*/false);
1075 OS << (NeedPlus ? " + " : "")
1081 OS << (NeedPlus ? " + " : "")
1083 BaseReg->printAsOperand(OS, /*PrintType=*/false);
1087 OS << (NeedPlus ? " + " : "")
1089 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1095 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1096 void ExtAddrMode::dump() const {
1102 /// \brief This class provides transaction based operation on the IR.
1103 /// Every change made through this class is recorded in the internal state and
1104 /// can be undone (rollback) until commit is called.
1105 class TypePromotionTransaction {
1107 /// \brief This represents the common interface of the individual transaction.
1108 /// Each class implements the logic for doing one specific modification on
1109 /// the IR via the TypePromotionTransaction.
1110 class TypePromotionAction {
1112 /// The Instruction modified.
1116 /// \brief Constructor of the action.
1117 /// The constructor performs the related action on the IR.
1118 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1120 virtual ~TypePromotionAction() {}
1122 /// \brief Undo the modification done by this action.
1123 /// When this method is called, the IR must be in the same state as it was
1124 /// before this action was applied.
1125 /// \pre Undoing the action works if and only if the IR is in the exact same
1126 /// state as it was directly after this action was applied.
1127 virtual void undo() = 0;
1129 /// \brief Advocate every change made by this action.
1130 /// When the results on the IR of the action are to be kept, it is important
1131 /// to call this function, otherwise hidden information may be kept forever.
1132 virtual void commit() {
1133 // Nothing to be done, this action is not doing anything.
1137 /// \brief Utility to remember the position of an instruction.
1138 class InsertionHandler {
1139 /// Position of an instruction.
1140 /// Either an instruction:
1141 /// - Is the first in a basic block: BB is used.
1142 /// - Has a previous instructon: PrevInst is used.
1144 Instruction *PrevInst;
1147 /// Remember whether or not the instruction had a previous instruction.
1148 bool HasPrevInstruction;
1151 /// \brief Record the position of \p Inst.
1152 InsertionHandler(Instruction *Inst) {
1153 BasicBlock::iterator It = Inst;
1154 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1155 if (HasPrevInstruction)
1156 Point.PrevInst = --It;
1158 Point.BB = Inst->getParent();
1161 /// \brief Insert \p Inst at the recorded position.
1162 void insert(Instruction *Inst) {
1163 if (HasPrevInstruction) {
1164 if (Inst->getParent())
1165 Inst->removeFromParent();
1166 Inst->insertAfter(Point.PrevInst);
1168 Instruction *Position = Point.BB->getFirstInsertionPt();
1169 if (Inst->getParent())
1170 Inst->moveBefore(Position);
1172 Inst->insertBefore(Position);
1177 /// \brief Move an instruction before another.
1178 class InstructionMoveBefore : public TypePromotionAction {
1179 /// Original position of the instruction.
1180 InsertionHandler Position;
1183 /// \brief Move \p Inst before \p Before.
1184 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1185 : TypePromotionAction(Inst), Position(Inst) {
1186 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1187 Inst->moveBefore(Before);
1190 /// \brief Move the instruction back to its original position.
1191 void undo() override {
1192 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1193 Position.insert(Inst);
1197 /// \brief Set the operand of an instruction with a new value.
1198 class OperandSetter : public TypePromotionAction {
1199 /// Original operand of the instruction.
1201 /// Index of the modified instruction.
1205 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1206 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1207 : TypePromotionAction(Inst), Idx(Idx) {
1208 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1209 << "for:" << *Inst << "\n"
1210 << "with:" << *NewVal << "\n");
1211 Origin = Inst->getOperand(Idx);
1212 Inst->setOperand(Idx, NewVal);
1215 /// \brief Restore the original value of the instruction.
1216 void undo() override {
1217 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1218 << "for: " << *Inst << "\n"
1219 << "with: " << *Origin << "\n");
1220 Inst->setOperand(Idx, Origin);
1224 /// \brief Hide the operands of an instruction.
1225 /// Do as if this instruction was not using any of its operands.
1226 class OperandsHider : public TypePromotionAction {
1227 /// The list of original operands.
1228 SmallVector<Value *, 4> OriginalValues;
1231 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1232 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1233 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1234 unsigned NumOpnds = Inst->getNumOperands();
1235 OriginalValues.reserve(NumOpnds);
1236 for (unsigned It = 0; It < NumOpnds; ++It) {
1237 // Save the current operand.
1238 Value *Val = Inst->getOperand(It);
1239 OriginalValues.push_back(Val);
1241 // We could use OperandSetter here, but that would implied an overhead
1242 // that we are not willing to pay.
1243 Inst->setOperand(It, UndefValue::get(Val->getType()));
1247 /// \brief Restore the original list of uses.
1248 void undo() override {
1249 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1250 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1251 Inst->setOperand(It, OriginalValues[It]);
1255 /// \brief Build a truncate instruction.
1256 class TruncBuilder : public TypePromotionAction {
1258 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1260 /// trunc Opnd to Ty.
1261 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1262 IRBuilder<> Builder(Opnd);
1263 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1264 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1267 /// \brief Get the built instruction.
1268 Instruction *getBuiltInstruction() { return Inst; }
1270 /// \brief Remove the built instruction.
1271 void undo() override {
1272 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1273 Inst->eraseFromParent();
1277 /// \brief Build a sign extension instruction.
1278 class SExtBuilder : public TypePromotionAction {
1280 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1282 /// sext Opnd to Ty.
1283 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1284 : TypePromotionAction(Inst) {
1285 IRBuilder<> Builder(InsertPt);
1286 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1287 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1290 /// \brief Get the built instruction.
1291 Instruction *getBuiltInstruction() { return Inst; }
1293 /// \brief Remove the built instruction.
1294 void undo() override {
1295 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1296 Inst->eraseFromParent();
1300 /// \brief Mutate an instruction to another type.
1301 class TypeMutator : public TypePromotionAction {
1302 /// Record the original type.
1306 /// \brief Mutate the type of \p Inst into \p NewTy.
1307 TypeMutator(Instruction *Inst, Type *NewTy)
1308 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1309 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1311 Inst->mutateType(NewTy);
1314 /// \brief Mutate the instruction back to its original type.
1315 void undo() override {
1316 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1318 Inst->mutateType(OrigTy);
1322 /// \brief Replace the uses of an instruction by another instruction.
1323 class UsesReplacer : public TypePromotionAction {
1324 /// Helper structure to keep track of the replaced uses.
1325 struct InstructionAndIdx {
1326 /// The instruction using the instruction.
1328 /// The index where this instruction is used for Inst.
1330 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1331 : Inst(Inst), Idx(Idx) {}
1334 /// Keep track of the original uses (pair Instruction, Index).
1335 SmallVector<InstructionAndIdx, 4> OriginalUses;
1336 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1339 /// \brief Replace all the use of \p Inst by \p New.
1340 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1341 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1343 // Record the original uses.
1344 for (Use &U : Inst->uses()) {
1345 Instruction *UserI = cast<Instruction>(U.getUser());
1346 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1348 // Now, we can replace the uses.
1349 Inst->replaceAllUsesWith(New);
1352 /// \brief Reassign the original uses of Inst to Inst.
1353 void undo() override {
1354 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1355 for (use_iterator UseIt = OriginalUses.begin(),
1356 EndIt = OriginalUses.end();
1357 UseIt != EndIt; ++UseIt) {
1358 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1363 /// \brief Remove an instruction from the IR.
1364 class InstructionRemover : public TypePromotionAction {
1365 /// Original position of the instruction.
1366 InsertionHandler Inserter;
1367 /// Helper structure to hide all the link to the instruction. In other
1368 /// words, this helps to do as if the instruction was removed.
1369 OperandsHider Hider;
1370 /// Keep track of the uses replaced, if any.
1371 UsesReplacer *Replacer;
1374 /// \brief Remove all reference of \p Inst and optinally replace all its
1376 /// \pre If !Inst->use_empty(), then New != nullptr
1377 InstructionRemover(Instruction *Inst, Value *New = nullptr)
1378 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1381 Replacer = new UsesReplacer(Inst, New);
1382 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1383 Inst->removeFromParent();
1386 ~InstructionRemover() { delete Replacer; }
1388 /// \brief Really remove the instruction.
1389 void commit() override { delete Inst; }
1391 /// \brief Resurrect the instruction and reassign it to the proper uses if
1392 /// new value was provided when build this action.
1393 void undo() override {
1394 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1395 Inserter.insert(Inst);
1403 /// Restoration point.
1404 /// The restoration point is a pointer to an action instead of an iterator
1405 /// because the iterator may be invalidated but not the pointer.
1406 typedef const TypePromotionAction *ConstRestorationPt;
1407 /// Advocate every changes made in that transaction.
1409 /// Undo all the changes made after the given point.
1410 void rollback(ConstRestorationPt Point);
1411 /// Get the current restoration point.
1412 ConstRestorationPt getRestorationPoint() const;
1414 /// \name API for IR modification with state keeping to support rollback.
1416 /// Same as Instruction::setOperand.
1417 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1418 /// Same as Instruction::eraseFromParent.
1419 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1420 /// Same as Value::replaceAllUsesWith.
1421 void replaceAllUsesWith(Instruction *Inst, Value *New);
1422 /// Same as Value::mutateType.
1423 void mutateType(Instruction *Inst, Type *NewTy);
1424 /// Same as IRBuilder::createTrunc.
1425 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1426 /// Same as IRBuilder::createSExt.
1427 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1428 /// Same as Instruction::moveBefore.
1429 void moveBefore(Instruction *Inst, Instruction *Before);
1433 /// The ordered list of actions made so far.
1434 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1435 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1438 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1441 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1444 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1447 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1450 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1452 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1455 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1456 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1459 Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1461 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1462 Instruction *I = Ptr->getBuiltInstruction();
1463 Actions.push_back(std::move(Ptr));
1467 Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1468 Value *Opnd, Type *Ty) {
1469 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1470 Instruction *I = Ptr->getBuiltInstruction();
1471 Actions.push_back(std::move(Ptr));
1475 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1476 Instruction *Before) {
1478 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1481 TypePromotionTransaction::ConstRestorationPt
1482 TypePromotionTransaction::getRestorationPoint() const {
1483 return !Actions.empty() ? Actions.back().get() : nullptr;
1486 void TypePromotionTransaction::commit() {
1487 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1493 void TypePromotionTransaction::rollback(
1494 TypePromotionTransaction::ConstRestorationPt Point) {
1495 while (!Actions.empty() && Point != Actions.back().get()) {
1496 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1501 /// \brief A helper class for matching addressing modes.
1503 /// This encapsulates the logic for matching the target-legal addressing modes.
1504 class AddressingModeMatcher {
1505 SmallVectorImpl<Instruction*> &AddrModeInsts;
1506 const TargetLowering &TLI;
1508 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1509 /// the memory instruction that we're computing this address for.
1511 Instruction *MemoryInst;
1513 /// AddrMode - This is the addressing mode that we're building up. This is
1514 /// part of the return value of this addressing mode matching stuff.
1515 ExtAddrMode &AddrMode;
1517 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1518 const SetOfInstrs &InsertedTruncs;
1519 /// A map from the instructions to their type before promotion.
1520 InstrToOrigTy &PromotedInsts;
1521 /// The ongoing transaction where every action should be registered.
1522 TypePromotionTransaction &TPT;
1524 /// IgnoreProfitability - This is set to true when we should not do
1525 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1526 /// always returns true.
1527 bool IgnoreProfitability;
1529 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1530 const TargetLowering &T, Type *AT,
1531 Instruction *MI, ExtAddrMode &AM,
1532 const SetOfInstrs &InsertedTruncs,
1533 InstrToOrigTy &PromotedInsts,
1534 TypePromotionTransaction &TPT)
1535 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1536 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1537 IgnoreProfitability = false;
1541 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1542 /// give an access type of AccessTy. This returns a list of involved
1543 /// instructions in AddrModeInsts.
1544 /// \p InsertedTruncs The truncate instruction inserted by other
1547 /// \p PromotedInsts maps the instructions to their type before promotion.
1548 /// \p The ongoing transaction where every action should be registered.
1549 static ExtAddrMode Match(Value *V, Type *AccessTy,
1550 Instruction *MemoryInst,
1551 SmallVectorImpl<Instruction*> &AddrModeInsts,
1552 const TargetLowering &TLI,
1553 const SetOfInstrs &InsertedTruncs,
1554 InstrToOrigTy &PromotedInsts,
1555 TypePromotionTransaction &TPT) {
1558 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1559 MemoryInst, Result, InsertedTruncs,
1560 PromotedInsts, TPT).MatchAddr(V, 0);
1561 (void)Success; assert(Success && "Couldn't select *anything*?");
1565 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1566 bool MatchAddr(Value *V, unsigned Depth);
1567 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1568 bool *MovedAway = nullptr);
1569 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1570 ExtAddrMode &AMBefore,
1571 ExtAddrMode &AMAfter);
1572 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1573 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1574 Value *PromotedOperand) const;
1577 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1578 /// Return true and update AddrMode if this addr mode is legal for the target,
1580 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1582 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1583 // mode. Just process that directly.
1585 return MatchAddr(ScaleReg, Depth);
1587 // If the scale is 0, it takes nothing to add this.
1591 // If we already have a scale of this value, we can add to it, otherwise, we
1592 // need an available scale field.
1593 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1596 ExtAddrMode TestAddrMode = AddrMode;
1598 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1599 // [A+B + A*7] -> [B+A*8].
1600 TestAddrMode.Scale += Scale;
1601 TestAddrMode.ScaledReg = ScaleReg;
1603 // If the new address isn't legal, bail out.
1604 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1607 // It was legal, so commit it.
1608 AddrMode = TestAddrMode;
1610 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1611 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1612 // X*Scale + C*Scale to addr mode.
1613 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
1614 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1615 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1616 TestAddrMode.ScaledReg = AddLHS;
1617 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1619 // If this addressing mode is legal, commit it and remember that we folded
1620 // this instruction.
1621 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1622 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1623 AddrMode = TestAddrMode;
1628 // Otherwise, not (x+c)*scale, just return what we have.
1632 /// MightBeFoldableInst - This is a little filter, which returns true if an
1633 /// addressing computation involving I might be folded into a load/store
1634 /// accessing it. This doesn't need to be perfect, but needs to accept at least
1635 /// the set of instructions that MatchOperationAddr can.
1636 static bool MightBeFoldableInst(Instruction *I) {
1637 switch (I->getOpcode()) {
1638 case Instruction::BitCast:
1639 case Instruction::AddrSpaceCast:
1640 // Don't touch identity bitcasts.
1641 if (I->getType() == I->getOperand(0)->getType())
1643 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1644 case Instruction::PtrToInt:
1645 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1647 case Instruction::IntToPtr:
1648 // We know the input is intptr_t, so this is foldable.
1650 case Instruction::Add:
1652 case Instruction::Mul:
1653 case Instruction::Shl:
1654 // Can only handle X*C and X << C.
1655 return isa<ConstantInt>(I->getOperand(1));
1656 case Instruction::GetElementPtr:
1663 /// \brief Hepler class to perform type promotion.
1664 class TypePromotionHelper {
1665 /// \brief Utility function to check whether or not a sign extension of
1666 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1667 /// using the operands of \p Inst or promoting \p Inst.
1668 /// In other words, check if:
1669 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1670 /// #1 Promotion applies:
1671 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1672 /// #2 Operand reuses:
1673 /// sext opnd1 to ConsideredSExtType.
1674 /// \p PromotedInsts maps the instructions to their type before promotion.
1675 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1676 const InstrToOrigTy &PromotedInsts);
1678 /// \brief Utility function to determine if \p OpIdx should be promoted when
1679 /// promoting \p Inst.
1680 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1681 if (isa<SelectInst>(Inst) && OpIdx == 0)
1686 /// \brief Utility function to promote the operand of \p SExt when this
1687 /// operand is a promotable trunc or sext.
1688 /// \p PromotedInsts maps the instructions to their type before promotion.
1689 /// \p CreatedInsts[out] contains how many non-free instructions have been
1690 /// created to promote the operand of SExt.
1691 /// Should never be called directly.
1692 /// \return The promoted value which is used instead of SExt.
1693 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1694 TypePromotionTransaction &TPT,
1695 InstrToOrigTy &PromotedInsts,
1696 unsigned &CreatedInsts);
1698 /// \brief Utility function to promote the operand of \p SExt when this
1699 /// operand is promotable and is not a supported trunc or sext.
1700 /// \p PromotedInsts maps the instructions to their type before promotion.
1701 /// \p CreatedInsts[out] contains how many non-free instructions have been
1702 /// created to promote the operand of SExt.
1703 /// Should never be called directly.
1704 /// \return The promoted value which is used instead of SExt.
1705 static Value *promoteOperandForOther(Instruction *SExt,
1706 TypePromotionTransaction &TPT,
1707 InstrToOrigTy &PromotedInsts,
1708 unsigned &CreatedInsts);
1711 /// Type for the utility function that promotes the operand of SExt.
1712 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1713 InstrToOrigTy &PromotedInsts,
1714 unsigned &CreatedInsts);
1715 /// \brief Given a sign extend instruction \p SExt, return the approriate
1716 /// action to promote the operand of \p SExt instead of using SExt.
1717 /// \return NULL if no promotable action is possible with the current
1719 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1720 /// the others CodeGenPrepare optimizations. This information is important
1721 /// because we do not want to promote these instructions as CodeGenPrepare
1722 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1723 /// \p PromotedInsts maps the instructions to their type before promotion.
1724 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1725 const TargetLowering &TLI,
1726 const InstrToOrigTy &PromotedInsts);
1729 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1730 Type *ConsideredSExtType,
1731 const InstrToOrigTy &PromotedInsts) {
1732 // We can always get through sext.
1733 if (isa<SExtInst>(Inst))
1736 // We can get through binary operator, if it is legal. In other words, the
1737 // binary operator must have a nuw or nsw flag.
1738 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1739 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1740 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1743 // Check if we can do the following simplification.
1744 // sext(trunc(sext)) --> sext
1745 if (!isa<TruncInst>(Inst))
1748 Value *OpndVal = Inst->getOperand(0);
1749 // Check if we can use this operand in the sext.
1750 // If the type is larger than the result type of the sign extension,
1752 if (OpndVal->getType()->getIntegerBitWidth() >
1753 ConsideredSExtType->getIntegerBitWidth())
1756 // If the operand of the truncate is not an instruction, we will not have
1757 // any information on the dropped bits.
1758 // (Actually we could for constant but it is not worth the extra logic).
1759 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1763 // Check if the source of the type is narrow enough.
1764 // I.e., check that trunc just drops sign extended bits.
1765 // #1 get the type of the operand.
1766 const Type *OpndType;
1767 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1768 if (It != PromotedInsts.end())
1769 OpndType = It->second;
1770 else if (isa<SExtInst>(Opnd))
1771 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1775 // #2 check that the truncate just drop sign extended bits.
1776 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1782 TypePromotionHelper::Action TypePromotionHelper::getAction(
1783 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1784 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1785 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1786 Type *SExtTy = SExt->getType();
1787 // If the operand of the sign extension is not an instruction, we cannot
1789 // If it, check we can get through.
1790 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1793 // Do not promote if the operand has been added by codegenprepare.
1794 // Otherwise, it means we are undoing an optimization that is likely to be
1795 // redone, thus causing potential infinite loop.
1796 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1799 // SExt or Trunc instructions.
1800 // Return the related handler.
1801 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1802 return promoteOperandForTruncAndSExt;
1804 // Regular instruction.
1805 // Abort early if we will have to insert non-free instructions.
1806 if (!SExtOpnd->hasOneUse() &&
1807 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1809 return promoteOperandForOther;
1812 Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1813 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1814 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1815 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1816 // get through it and this method should not be called.
1817 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1818 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1820 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1823 // Remove dead code.
1824 if (SExtOpnd->use_empty())
1825 TPT.eraseInstruction(SExtOpnd);
1827 // Check if the sext is still needed.
1828 if (SExt->getType() != SExt->getOperand(0)->getType())
1831 // At this point we have: sext ty opnd to ty.
1832 // Reassign the uses of SExt to the opnd and remove SExt.
1833 Value *NextVal = SExt->getOperand(0);
1834 TPT.eraseInstruction(SExt, NextVal);
1839 TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1840 TypePromotionTransaction &TPT,
1841 InstrToOrigTy &PromotedInsts,
1842 unsigned &CreatedInsts) {
1843 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1844 // get through it and this method should not be called.
1845 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1847 if (!SExtOpnd->hasOneUse()) {
1848 // SExtOpnd will be promoted.
1849 // All its uses, but SExt, will need to use a truncated value of the
1850 // promoted version.
1851 // Create the truncate now.
1852 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1853 Trunc->removeFromParent();
1854 // Insert it just after the definition.
1855 Trunc->insertAfter(SExtOpnd);
1857 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1858 // Restore the operand of SExt (which has been replace by the previous call
1859 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1860 TPT.setOperand(SExt, 0, SExtOpnd);
1863 // Get through the Instruction:
1864 // 1. Update its type.
1865 // 2. Replace the uses of SExt by Inst.
1866 // 3. Sign extend each operand that needs to be sign extended.
1868 // Remember the original type of the instruction before promotion.
1869 // This is useful to know that the high bits are sign extended bits.
1870 PromotedInsts.insert(
1871 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1873 TPT.mutateType(SExtOpnd, SExt->getType());
1875 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1877 Instruction *SExtForOpnd = SExt;
1879 DEBUG(dbgs() << "Propagate SExt to operands\n");
1880 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1882 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1883 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1884 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1885 DEBUG(dbgs() << "No need to propagate\n");
1888 // Check if we can statically sign extend the operand.
1889 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1890 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1891 DEBUG(dbgs() << "Statically sign extend\n");
1894 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1897 // UndefValue are typed, so we have to statically sign extend them.
1898 if (isa<UndefValue>(Opnd)) {
1899 DEBUG(dbgs() << "Statically sign extend\n");
1900 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1904 // Otherwise we have to explicity sign extend the operand.
1905 // Check if SExt was reused to sign extend an operand.
1907 // If yes, create a new one.
1908 DEBUG(dbgs() << "More operands to sext\n");
1909 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1913 TPT.setOperand(SExtForOpnd, 0, Opnd);
1915 // Move the sign extension before the insertion point.
1916 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1917 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1918 // If more sext are required, new instructions will have to be created.
1919 SExtForOpnd = nullptr;
1921 if (SExtForOpnd == SExt) {
1922 DEBUG(dbgs() << "Sign extension is useless now\n");
1923 TPT.eraseInstruction(SExt);
1928 /// IsPromotionProfitable - Check whether or not promoting an instruction
1929 /// to a wider type was profitable.
1930 /// \p MatchedSize gives the number of instructions that have been matched
1931 /// in the addressing mode after the promotion was applied.
1932 /// \p SizeWithPromotion gives the number of created instructions for
1933 /// the promotion plus the number of instructions that have been
1934 /// matched in the addressing mode before the promotion.
1935 /// \p PromotedOperand is the value that has been promoted.
1936 /// \return True if the promotion is profitable, false otherwise.
1938 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1939 unsigned SizeWithPromotion,
1940 Value *PromotedOperand) const {
1941 // We folded less instructions than what we created to promote the operand.
1942 // This is not profitable.
1943 if (MatchedSize < SizeWithPromotion)
1945 if (MatchedSize > SizeWithPromotion)
1947 // The promotion is neutral but it may help folding the sign extension in
1948 // loads for instance.
1949 // Check that we did not create an illegal instruction.
1950 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1953 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1954 // If the ISDOpcode is undefined, it was undefined before the promotion.
1957 // Otherwise, check if the promoted instruction is legal or not.
1958 return TLI.isOperationLegalOrCustom(ISDOpcode,
1959 EVT::getEVT(PromotedInst->getType()));
1962 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
1963 /// fold the operation into the addressing mode. If so, update the addressing
1964 /// mode and return true, otherwise return false without modifying AddrMode.
1965 /// If \p MovedAway is not NULL, it contains the information of whether or
1966 /// not AddrInst has to be folded into the addressing mode on success.
1967 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1968 /// because it has been moved away.
1969 /// Thus AddrInst must not be added in the matched instructions.
1970 /// This state can happen when AddrInst is a sext, since it may be moved away.
1971 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
1972 /// not be referenced anymore.
1973 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1976 // Avoid exponential behavior on extremely deep expression trees.
1977 if (Depth >= 5) return false;
1979 // By default, all matched instructions stay in place.
1984 case Instruction::PtrToInt:
1985 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1986 return MatchAddr(AddrInst->getOperand(0), Depth);
1987 case Instruction::IntToPtr:
1988 // This inttoptr is a no-op if the integer type is pointer sized.
1989 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
1990 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
1991 return MatchAddr(AddrInst->getOperand(0), Depth);
1993 case Instruction::BitCast:
1994 case Instruction::AddrSpaceCast:
1995 // BitCast is always a noop, and we can handle it as long as it is
1996 // int->int or pointer->pointer (we don't want int<->fp or something).
1997 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1998 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1999 // Don't touch identity bitcasts. These were probably put here by LSR,
2000 // and we don't want to mess around with them. Assume it knows what it
2002 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2003 return MatchAddr(AddrInst->getOperand(0), Depth);
2005 case Instruction::Add: {
2006 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2007 ExtAddrMode BackupAddrMode = AddrMode;
2008 unsigned OldSize = AddrModeInsts.size();
2009 // Start a transaction at this point.
2010 // The LHS may match but not the RHS.
2011 // Therefore, we need a higher level restoration point to undo partially
2012 // matched operation.
2013 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2014 TPT.getRestorationPoint();
2016 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2017 MatchAddr(AddrInst->getOperand(0), Depth+1))
2020 // Restore the old addr mode info.
2021 AddrMode = BackupAddrMode;
2022 AddrModeInsts.resize(OldSize);
2023 TPT.rollback(LastKnownGood);
2025 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2026 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2027 MatchAddr(AddrInst->getOperand(1), Depth+1))
2030 // Otherwise we definitely can't merge the ADD in.
2031 AddrMode = BackupAddrMode;
2032 AddrModeInsts.resize(OldSize);
2033 TPT.rollback(LastKnownGood);
2036 //case Instruction::Or:
2037 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2039 case Instruction::Mul:
2040 case Instruction::Shl: {
2041 // Can only handle X*C and X << C.
2042 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2045 int64_t Scale = RHS->getSExtValue();
2046 if (Opcode == Instruction::Shl)
2047 Scale = 1LL << Scale;
2049 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2051 case Instruction::GetElementPtr: {
2052 // Scan the GEP. We check it if it contains constant offsets and at most
2053 // one variable offset.
2054 int VariableOperand = -1;
2055 unsigned VariableScale = 0;
2057 int64_t ConstantOffset = 0;
2058 const DataLayout *TD = TLI.getDataLayout();
2059 gep_type_iterator GTI = gep_type_begin(AddrInst);
2060 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2061 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2062 const StructLayout *SL = TD->getStructLayout(STy);
2064 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2065 ConstantOffset += SL->getElementOffset(Idx);
2067 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2068 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2069 ConstantOffset += CI->getSExtValue()*TypeSize;
2070 } else if (TypeSize) { // Scales of zero don't do anything.
2071 // We only allow one variable index at the moment.
2072 if (VariableOperand != -1)
2075 // Remember the variable index.
2076 VariableOperand = i;
2077 VariableScale = TypeSize;
2082 // A common case is for the GEP to only do a constant offset. In this case,
2083 // just add it to the disp field and check validity.
2084 if (VariableOperand == -1) {
2085 AddrMode.BaseOffs += ConstantOffset;
2086 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2087 // Check to see if we can fold the base pointer in too.
2088 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2091 AddrMode.BaseOffs -= ConstantOffset;
2095 // Save the valid addressing mode in case we can't match.
2096 ExtAddrMode BackupAddrMode = AddrMode;
2097 unsigned OldSize = AddrModeInsts.size();
2099 // See if the scale and offset amount is valid for this target.
2100 AddrMode.BaseOffs += ConstantOffset;
2102 // Match the base operand of the GEP.
2103 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2104 // If it couldn't be matched, just stuff the value in a register.
2105 if (AddrMode.HasBaseReg) {
2106 AddrMode = BackupAddrMode;
2107 AddrModeInsts.resize(OldSize);
2110 AddrMode.HasBaseReg = true;
2111 AddrMode.BaseReg = AddrInst->getOperand(0);
2114 // Match the remaining variable portion of the GEP.
2115 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2117 // If it couldn't be matched, try stuffing the base into a register
2118 // instead of matching it, and retrying the match of the scale.
2119 AddrMode = BackupAddrMode;
2120 AddrModeInsts.resize(OldSize);
2121 if (AddrMode.HasBaseReg)
2123 AddrMode.HasBaseReg = true;
2124 AddrMode.BaseReg = AddrInst->getOperand(0);
2125 AddrMode.BaseOffs += ConstantOffset;
2126 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2127 VariableScale, Depth)) {
2128 // If even that didn't work, bail.
2129 AddrMode = BackupAddrMode;
2130 AddrModeInsts.resize(OldSize);
2137 case Instruction::SExt: {
2138 Instruction *SExt = dyn_cast<Instruction>(AddrInst);
2142 // Try to move this sext out of the way of the addressing mode.
2143 // Ask for a method for doing so.
2144 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
2145 SExt, InsertedTruncs, TLI, PromotedInsts);
2149 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2150 TPT.getRestorationPoint();
2151 unsigned CreatedInsts = 0;
2152 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
2153 // SExt has been moved away.
2154 // Thus either it will be rematched later in the recursive calls or it is
2155 // gone. Anyway, we must not fold it into the addressing mode at this point.
2159 // addr = gep base, idx
2161 // promotedOpnd = sext opnd <- no match here
2162 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2163 // addr = gep base, op <- match
2167 assert(PromotedOperand &&
2168 "TypePromotionHelper should have filtered out those cases");
2170 ExtAddrMode BackupAddrMode = AddrMode;
2171 unsigned OldSize = AddrModeInsts.size();
2173 if (!MatchAddr(PromotedOperand, Depth) ||
2174 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2176 AddrMode = BackupAddrMode;
2177 AddrModeInsts.resize(OldSize);
2178 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2179 TPT.rollback(LastKnownGood);
2188 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2189 /// addressing mode. If Addr can't be added to AddrMode this returns false and
2190 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2191 /// or intptr_t for the target.
2193 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2194 // Start a transaction at this point that we will rollback if the matching
2196 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2197 TPT.getRestorationPoint();
2198 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2199 // Fold in immediates if legal for the target.
2200 AddrMode.BaseOffs += CI->getSExtValue();
2201 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2203 AddrMode.BaseOffs -= CI->getSExtValue();
2204 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2205 // If this is a global variable, try to fold it into the addressing mode.
2206 if (!AddrMode.BaseGV) {
2207 AddrMode.BaseGV = GV;
2208 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2210 AddrMode.BaseGV = nullptr;
2212 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2213 ExtAddrMode BackupAddrMode = AddrMode;
2214 unsigned OldSize = AddrModeInsts.size();
2216 // Check to see if it is possible to fold this operation.
2217 bool MovedAway = false;
2218 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2219 // This instruction may have been move away. If so, there is nothing
2223 // Okay, it's possible to fold this. Check to see if it is actually
2224 // *profitable* to do so. We use a simple cost model to avoid increasing
2225 // register pressure too much.
2226 if (I->hasOneUse() ||
2227 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2228 AddrModeInsts.push_back(I);
2232 // It isn't profitable to do this, roll back.
2233 //cerr << "NOT FOLDING: " << *I;
2234 AddrMode = BackupAddrMode;
2235 AddrModeInsts.resize(OldSize);
2236 TPT.rollback(LastKnownGood);
2238 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2239 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2241 TPT.rollback(LastKnownGood);
2242 } else if (isa<ConstantPointerNull>(Addr)) {
2243 // Null pointer gets folded without affecting the addressing mode.
2247 // Worse case, the target should support [reg] addressing modes. :)
2248 if (!AddrMode.HasBaseReg) {
2249 AddrMode.HasBaseReg = true;
2250 AddrMode.BaseReg = Addr;
2251 // Still check for legality in case the target supports [imm] but not [i+r].
2252 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2254 AddrMode.HasBaseReg = false;
2255 AddrMode.BaseReg = nullptr;
2258 // If the base register is already taken, see if we can do [r+r].
2259 if (AddrMode.Scale == 0) {
2261 AddrMode.ScaledReg = Addr;
2262 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2265 AddrMode.ScaledReg = nullptr;
2268 TPT.rollback(LastKnownGood);
2272 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2273 /// inline asm call are due to memory operands. If so, return true, otherwise
2275 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2276 const TargetLowering &TLI) {
2277 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2278 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2279 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2281 // Compute the constraint code and ConstraintType to use.
2282 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2284 // If this asm operand is our Value*, and if it isn't an indirect memory
2285 // operand, we can't fold it!
2286 if (OpInfo.CallOperandVal == OpVal &&
2287 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2288 !OpInfo.isIndirect))
2295 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2296 /// memory use. If we find an obviously non-foldable instruction, return true.
2297 /// Add the ultimately found memory instructions to MemoryUses.
2298 static bool FindAllMemoryUses(Instruction *I,
2299 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2300 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
2301 const TargetLowering &TLI) {
2302 // If we already considered this instruction, we're done.
2303 if (!ConsideredInsts.insert(I))
2306 // If this is an obviously unfoldable instruction, bail out.
2307 if (!MightBeFoldableInst(I))
2310 // Loop over all the uses, recursively processing them.
2311 for (Use &U : I->uses()) {
2312 Instruction *UserI = cast<Instruction>(U.getUser());
2314 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2315 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2319 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2320 unsigned opNo = U.getOperandNo();
2321 if (opNo == 0) return true; // Storing addr, not into addr.
2322 MemoryUses.push_back(std::make_pair(SI, opNo));
2326 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2327 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2328 if (!IA) return true;
2330 // If this is a memory operand, we're cool, otherwise bail out.
2331 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2336 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2343 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2344 /// the use site that we're folding it into. If so, there is no cost to
2345 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2346 /// that we know are live at the instruction already.
2347 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2348 Value *KnownLive2) {
2349 // If Val is either of the known-live values, we know it is live!
2350 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2353 // All values other than instructions and arguments (e.g. constants) are live.
2354 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2356 // If Val is a constant sized alloca in the entry block, it is live, this is
2357 // true because it is just a reference to the stack/frame pointer, which is
2358 // live for the whole function.
2359 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2360 if (AI->isStaticAlloca())
2363 // Check to see if this value is already used in the memory instruction's
2364 // block. If so, it's already live into the block at the very least, so we
2365 // can reasonably fold it.
2366 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2369 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2370 /// mode of the machine to fold the specified instruction into a load or store
2371 /// that ultimately uses it. However, the specified instruction has multiple
2372 /// uses. Given this, it may actually increase register pressure to fold it
2373 /// into the load. For example, consider this code:
2377 /// use(Y) -> nonload/store
2381 /// In this case, Y has multiple uses, and can be folded into the load of Z
2382 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2383 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2384 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2385 /// number of computations either.
2387 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2388 /// X was live across 'load Z' for other reasons, we actually *would* want to
2389 /// fold the addressing mode in the Z case. This would make Y die earlier.
2390 bool AddressingModeMatcher::
2391 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2392 ExtAddrMode &AMAfter) {
2393 if (IgnoreProfitability) return true;
2395 // AMBefore is the addressing mode before this instruction was folded into it,
2396 // and AMAfter is the addressing mode after the instruction was folded. Get
2397 // the set of registers referenced by AMAfter and subtract out those
2398 // referenced by AMBefore: this is the set of values which folding in this
2399 // address extends the lifetime of.
2401 // Note that there are only two potential values being referenced here,
2402 // BaseReg and ScaleReg (global addresses are always available, as are any
2403 // folded immediates).
2404 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2406 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2407 // lifetime wasn't extended by adding this instruction.
2408 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2410 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2411 ScaledReg = nullptr;
2413 // If folding this instruction (and it's subexprs) didn't extend any live
2414 // ranges, we're ok with it.
2415 if (!BaseReg && !ScaledReg)
2418 // If all uses of this instruction are ultimately load/store/inlineasm's,
2419 // check to see if their addressing modes will include this instruction. If
2420 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2422 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2423 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2424 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2425 return false; // Has a non-memory, non-foldable use!
2427 // Now that we know that all uses of this instruction are part of a chain of
2428 // computation involving only operations that could theoretically be folded
2429 // into a memory use, loop over each of these uses and see if they could
2430 // *actually* fold the instruction.
2431 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2432 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2433 Instruction *User = MemoryUses[i].first;
2434 unsigned OpNo = MemoryUses[i].second;
2436 // Get the access type of this use. If the use isn't a pointer, we don't
2437 // know what it accesses.
2438 Value *Address = User->getOperand(OpNo);
2439 if (!Address->getType()->isPointerTy())
2441 Type *AddressAccessTy = Address->getType()->getPointerElementType();
2443 // Do a match against the root of this address, ignoring profitability. This
2444 // will tell us if the addressing mode for the memory operation will
2445 // *actually* cover the shared instruction.
2447 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2448 TPT.getRestorationPoint();
2449 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2450 MemoryInst, Result, InsertedTruncs,
2451 PromotedInsts, TPT);
2452 Matcher.IgnoreProfitability = true;
2453 bool Success = Matcher.MatchAddr(Address, 0);
2454 (void)Success; assert(Success && "Couldn't select *anything*?");
2456 // The match was to check the profitability, the changes made are not
2457 // part of the original matcher. Therefore, they should be dropped
2458 // otherwise the original matcher will not present the right state.
2459 TPT.rollback(LastKnownGood);
2461 // If the match didn't cover I, then it won't be shared by it.
2462 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2463 I) == MatchedAddrModeInsts.end())
2466 MatchedAddrModeInsts.clear();
2472 } // end anonymous namespace
2474 /// IsNonLocalValue - Return true if the specified values are defined in a
2475 /// different basic block than BB.
2476 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2477 if (Instruction *I = dyn_cast<Instruction>(V))
2478 return I->getParent() != BB;
2482 /// OptimizeMemoryInst - Load and Store Instructions often have
2483 /// addressing modes that can do significant amounts of computation. As such,
2484 /// instruction selection will try to get the load or store to do as much
2485 /// computation as possible for the program. The problem is that isel can only
2486 /// see within a single block. As such, we sink as much legal addressing mode
2487 /// stuff into the block as possible.
2489 /// This method is used to optimize both load/store and inline asms with memory
2491 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2495 // Try to collapse single-value PHI nodes. This is necessary to undo
2496 // unprofitable PRE transformations.
2497 SmallVector<Value*, 8> worklist;
2498 SmallPtrSet<Value*, 16> Visited;
2499 worklist.push_back(Addr);
2501 // Use a worklist to iteratively look through PHI nodes, and ensure that
2502 // the addressing mode obtained from the non-PHI roots of the graph
2504 Value *Consensus = nullptr;
2505 unsigned NumUsesConsensus = 0;
2506 bool IsNumUsesConsensusValid = false;
2507 SmallVector<Instruction*, 16> AddrModeInsts;
2508 ExtAddrMode AddrMode;
2509 TypePromotionTransaction TPT;
2510 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2511 TPT.getRestorationPoint();
2512 while (!worklist.empty()) {
2513 Value *V = worklist.back();
2514 worklist.pop_back();
2516 // Break use-def graph loops.
2517 if (!Visited.insert(V)) {
2518 Consensus = nullptr;
2522 // For a PHI node, push all of its incoming values.
2523 if (PHINode *P = dyn_cast<PHINode>(V)) {
2524 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2525 worklist.push_back(P->getIncomingValue(i));
2529 // For non-PHIs, determine the addressing mode being computed.
2530 SmallVector<Instruction*, 16> NewAddrModeInsts;
2531 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2532 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2533 PromotedInsts, TPT);
2535 // This check is broken into two cases with very similar code to avoid using
2536 // getNumUses() as much as possible. Some values have a lot of uses, so
2537 // calling getNumUses() unconditionally caused a significant compile-time
2541 AddrMode = NewAddrMode;
2542 AddrModeInsts = NewAddrModeInsts;
2544 } else if (NewAddrMode == AddrMode) {
2545 if (!IsNumUsesConsensusValid) {
2546 NumUsesConsensus = Consensus->getNumUses();
2547 IsNumUsesConsensusValid = true;
2550 // Ensure that the obtained addressing mode is equivalent to that obtained
2551 // for all other roots of the PHI traversal. Also, when choosing one
2552 // such root as representative, select the one with the most uses in order
2553 // to keep the cost modeling heuristics in AddressingModeMatcher
2555 unsigned NumUses = V->getNumUses();
2556 if (NumUses > NumUsesConsensus) {
2558 NumUsesConsensus = NumUses;
2559 AddrModeInsts = NewAddrModeInsts;
2564 Consensus = nullptr;
2568 // If the addressing mode couldn't be determined, or if multiple different
2569 // ones were determined, bail out now.
2571 TPT.rollback(LastKnownGood);
2576 // Check to see if any of the instructions supersumed by this addr mode are
2577 // non-local to I's BB.
2578 bool AnyNonLocal = false;
2579 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2580 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2586 // If all the instructions matched are already in this BB, don't do anything.
2588 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
2592 // Insert this computation right after this user. Since our caller is
2593 // scanning from the top of the BB to the bottom, reuse of the expr are
2594 // guaranteed to happen later.
2595 IRBuilder<> Builder(MemoryInst);
2597 // Now that we determined the addressing expression we want to use and know
2598 // that we have to sink it into this block. Check to see if we have already
2599 // done this for some other load/store instr in this block. If so, reuse the
2601 Value *&SunkAddr = SunkAddrs[Addr];
2603 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2604 << *MemoryInst << "\n");
2605 if (SunkAddr->getType() != Addr->getType())
2606 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2607 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2608 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2609 // By default, we use the GEP-based method when AA is used later. This
2610 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2611 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2612 << *MemoryInst << "\n");
2613 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2614 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
2616 // First, find the pointer.
2617 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2618 ResultPtr = AddrMode.BaseReg;
2619 AddrMode.BaseReg = nullptr;
2622 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2623 // We can't add more than one pointer together, nor can we scale a
2624 // pointer (both of which seem meaningless).
2625 if (ResultPtr || AddrMode.Scale != 1)
2628 ResultPtr = AddrMode.ScaledReg;
2632 if (AddrMode.BaseGV) {
2636 ResultPtr = AddrMode.BaseGV;
2639 // If the real base value actually came from an inttoptr, then the matcher
2640 // will look through it and provide only the integer value. In that case,
2642 if (!ResultPtr && AddrMode.BaseReg) {
2644 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2645 AddrMode.BaseReg = nullptr;
2646 } else if (!ResultPtr && AddrMode.Scale == 1) {
2648 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2653 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2654 SunkAddr = Constant::getNullValue(Addr->getType());
2655 } else if (!ResultPtr) {
2659 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2661 // Start with the base register. Do this first so that subsequent address
2662 // matching finds it last, which will prevent it from trying to match it
2663 // as the scaled value in case it happens to be a mul. That would be
2664 // problematic if we've sunk a different mul for the scale, because then
2665 // we'd end up sinking both muls.
2666 if (AddrMode.BaseReg) {
2667 Value *V = AddrMode.BaseReg;
2668 if (V->getType() != IntPtrTy)
2669 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2674 // Add the scale value.
2675 if (AddrMode.Scale) {
2676 Value *V = AddrMode.ScaledReg;
2677 if (V->getType() == IntPtrTy) {
2679 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2680 cast<IntegerType>(V->getType())->getBitWidth()) {
2681 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2683 // It is only safe to sign extend the BaseReg if we know that the math
2684 // required to create it did not overflow before we extend it. Since
2685 // the original IR value was tossed in favor of a constant back when
2686 // the AddrMode was created we need to bail out gracefully if widths
2687 // do not match instead of extending it.
2688 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2689 if (I && (ResultIndex != AddrMode.BaseReg))
2690 I->eraseFromParent();
2694 if (AddrMode.Scale != 1)
2695 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2698 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2703 // Add in the Base Offset if present.
2704 if (AddrMode.BaseOffs) {
2705 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2707 // We need to add this separately from the scale above to help with
2708 // SDAG consecutive load/store merging.
2709 if (ResultPtr->getType() != I8PtrTy)
2710 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2711 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2718 SunkAddr = ResultPtr;
2720 if (ResultPtr->getType() != I8PtrTy)
2721 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2722 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2725 if (SunkAddr->getType() != Addr->getType())
2726 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2729 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2730 << *MemoryInst << "\n");
2731 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2732 Value *Result = nullptr;
2734 // Start with the base register. Do this first so that subsequent address
2735 // matching finds it last, which will prevent it from trying to match it
2736 // as the scaled value in case it happens to be a mul. That would be
2737 // problematic if we've sunk a different mul for the scale, because then
2738 // we'd end up sinking both muls.
2739 if (AddrMode.BaseReg) {
2740 Value *V = AddrMode.BaseReg;
2741 if (V->getType()->isPointerTy())
2742 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2743 if (V->getType() != IntPtrTy)
2744 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2748 // Add the scale value.
2749 if (AddrMode.Scale) {
2750 Value *V = AddrMode.ScaledReg;
2751 if (V->getType() == IntPtrTy) {
2753 } else if (V->getType()->isPointerTy()) {
2754 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2755 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2756 cast<IntegerType>(V->getType())->getBitWidth()) {
2757 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2759 // It is only safe to sign extend the BaseReg if we know that the math
2760 // required to create it did not overflow before we extend it. Since
2761 // the original IR value was tossed in favor of a constant back when
2762 // the AddrMode was created we need to bail out gracefully if widths
2763 // do not match instead of extending it.
2764 Instruction *I = dyn_cast_or_null<Instruction>(Result);
2765 if (I && (Result != AddrMode.BaseReg))
2766 I->eraseFromParent();
2769 if (AddrMode.Scale != 1)
2770 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2773 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2778 // Add in the BaseGV if present.
2779 if (AddrMode.BaseGV) {
2780 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2782 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2787 // Add in the Base Offset if present.
2788 if (AddrMode.BaseOffs) {
2789 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2791 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2797 SunkAddr = Constant::getNullValue(Addr->getType());
2799 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2802 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2804 // If we have no uses, recursively delete the value and all dead instructions
2806 if (Repl->use_empty()) {
2807 // This can cause recursive deletion, which can invalidate our iterator.
2808 // Use a WeakVH to hold onto it in case this happens.
2809 WeakVH IterHandle(CurInstIterator);
2810 BasicBlock *BB = CurInstIterator->getParent();
2812 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2814 if (IterHandle != CurInstIterator) {
2815 // If the iterator instruction was recursively deleted, start over at the
2816 // start of the block.
2817 CurInstIterator = BB->begin();
2825 /// OptimizeInlineAsmInst - If there are any memory operands, use
2826 /// OptimizeMemoryInst to sink their address computing into the block when
2827 /// possible / profitable.
2828 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2829 bool MadeChange = false;
2831 TargetLowering::AsmOperandInfoVector
2832 TargetConstraints = TLI->ParseConstraints(CS);
2834 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2835 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2837 // Compute the constraint code and ConstraintType to use.
2838 TLI->ComputeConstraintToUse(OpInfo, SDValue());
2840 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2841 OpInfo.isIndirect) {
2842 Value *OpVal = CS->getArgOperand(ArgNo++);
2843 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2844 } else if (OpInfo.Type == InlineAsm::isInput)
2851 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2852 /// basic block as the load, unless conditions are unfavorable. This allows
2853 /// SelectionDAG to fold the extend into the load.
2855 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2856 // Look for a load being extended.
2857 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2858 if (!LI) return false;
2860 // If they're already in the same block, there's nothing to do.
2861 if (LI->getParent() == I->getParent())
2864 // If the load has other users and the truncate is not free, this probably
2865 // isn't worthwhile.
2866 if (!LI->hasOneUse() &&
2867 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2868 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
2869 !TLI->isTruncateFree(I->getType(), LI->getType()))
2872 // Check whether the target supports casts folded into loads.
2874 if (isa<ZExtInst>(I))
2875 LType = ISD::ZEXTLOAD;
2877 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2878 LType = ISD::SEXTLOAD;
2880 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
2883 // Move the extend into the same block as the load, so that SelectionDAG
2885 I->removeFromParent();
2891 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2892 BasicBlock *DefBB = I->getParent();
2894 // If the result of a {s|z}ext and its source are both live out, rewrite all
2895 // other uses of the source with result of extension.
2896 Value *Src = I->getOperand(0);
2897 if (Src->hasOneUse())
2900 // Only do this xform if truncating is free.
2901 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
2904 // Only safe to perform the optimization if the source is also defined in
2906 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
2909 bool DefIsLiveOut = false;
2910 for (User *U : I->users()) {
2911 Instruction *UI = cast<Instruction>(U);
2913 // Figure out which BB this ext is used in.
2914 BasicBlock *UserBB = UI->getParent();
2915 if (UserBB == DefBB) continue;
2916 DefIsLiveOut = true;
2922 // Make sure none of the uses are PHI nodes.
2923 for (User *U : Src->users()) {
2924 Instruction *UI = cast<Instruction>(U);
2925 BasicBlock *UserBB = UI->getParent();
2926 if (UserBB == DefBB) continue;
2927 // Be conservative. We don't want this xform to end up introducing
2928 // reloads just before load / store instructions.
2929 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
2933 // InsertedTruncs - Only insert one trunc in each block once.
2934 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2936 bool MadeChange = false;
2937 for (Use &U : Src->uses()) {
2938 Instruction *User = cast<Instruction>(U.getUser());
2940 // Figure out which BB this ext is used in.
2941 BasicBlock *UserBB = User->getParent();
2942 if (UserBB == DefBB) continue;
2944 // Both src and def are live in this block. Rewrite the use.
2945 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2947 if (!InsertedTrunc) {
2948 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2949 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
2950 InsertedTruncsSet.insert(InsertedTrunc);
2953 // Replace a use of the {s|z}ext source with a use of the result.
2962 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2963 /// turned into an explicit branch.
2964 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2965 // FIXME: This should use the same heuristics as IfConversion to determine
2966 // whether a select is better represented as a branch. This requires that
2967 // branch probability metadata is preserved for the select, which is not the
2970 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2972 // If the branch is predicted right, an out of order CPU can avoid blocking on
2973 // the compare. Emit cmovs on compares with a memory operand as branches to
2974 // avoid stalls on the load from memory. If the compare has more than one use
2975 // there's probably another cmov or setcc around so it's not worth emitting a
2980 Value *CmpOp0 = Cmp->getOperand(0);
2981 Value *CmpOp1 = Cmp->getOperand(1);
2983 // We check that the memory operand has one use to avoid uses of the loaded
2984 // value directly after the compare, making branches unprofitable.
2985 return Cmp->hasOneUse() &&
2986 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2987 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2991 /// If we have a SelectInst that will likely profit from branch prediction,
2992 /// turn it into a branch.
2993 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
2994 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2996 // Can we convert the 'select' to CF ?
2997 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3000 TargetLowering::SelectSupportKind SelectKind;
3002 SelectKind = TargetLowering::VectorMaskSelect;
3003 else if (SI->getType()->isVectorTy())
3004 SelectKind = TargetLowering::ScalarCondVectorVal;
3006 SelectKind = TargetLowering::ScalarValSelect;
3008 // Do we have efficient codegen support for this kind of 'selects' ?
3009 if (TLI->isSelectSupported(SelectKind)) {
3010 // We have efficient codegen support for the select instruction.
3011 // Check if it is profitable to keep this 'select'.
3012 if (!TLI->isPredictableSelectExpensive() ||
3013 !isFormingBranchFromSelectProfitable(SI))
3019 // First, we split the block containing the select into 2 blocks.
3020 BasicBlock *StartBlock = SI->getParent();
3021 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3022 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3024 // Create a new block serving as the landing pad for the branch.
3025 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3026 NextBlock->getParent(), NextBlock);
3028 // Move the unconditional branch from the block with the select in it into our
3029 // landing pad block.
3030 StartBlock->getTerminator()->eraseFromParent();
3031 BranchInst::Create(NextBlock, SmallBlock);
3033 // Insert the real conditional branch based on the original condition.
3034 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3036 // The select itself is replaced with a PHI Node.
3037 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3039 PN->addIncoming(SI->getTrueValue(), StartBlock);
3040 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3041 SI->replaceAllUsesWith(PN);
3042 SI->eraseFromParent();
3044 // Instruct OptimizeBlock to skip to the next block.
3045 CurInstIterator = StartBlock->end();
3046 ++NumSelectsExpanded;
3050 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3051 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3053 for (unsigned i = 0; i < Mask.size(); ++i) {
3054 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3056 SplatElem = Mask[i];
3062 /// Some targets have expensive vector shifts if the lanes aren't all the same
3063 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3064 /// it's often worth sinking a shufflevector splat down to its use so that
3065 /// codegen can spot all lanes are identical.
3066 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3067 BasicBlock *DefBB = SVI->getParent();
3069 // Only do this xform if variable vector shifts are particularly expensive.
3070 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3073 // We only expect better codegen by sinking a shuffle if we can recognise a
3075 if (!isBroadcastShuffle(SVI))
3078 // InsertedShuffles - Only insert a shuffle in each block once.
3079 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3081 bool MadeChange = false;
3082 for (User *U : SVI->users()) {
3083 Instruction *UI = cast<Instruction>(U);
3085 // Figure out which BB this ext is used in.
3086 BasicBlock *UserBB = UI->getParent();
3087 if (UserBB == DefBB) continue;
3089 // For now only apply this when the splat is used by a shift instruction.
3090 if (!UI->isShift()) continue;
3092 // Everything checks out, sink the shuffle if the user's block doesn't
3093 // already have a copy.
3094 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3096 if (!InsertedShuffle) {
3097 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3098 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3100 SVI->getOperand(2), "", InsertPt);
3103 UI->replaceUsesOfWith(SVI, InsertedShuffle);
3107 // If we removed all uses, nuke the shuffle.
3108 if (SVI->use_empty()) {
3109 SVI->eraseFromParent();
3116 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
3117 if (PHINode *P = dyn_cast<PHINode>(I)) {
3118 // It is possible for very late stage optimizations (such as SimplifyCFG)
3119 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3120 // trivial PHI, go ahead and zap it here.
3121 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
3123 P->replaceAllUsesWith(V);
3124 P->eraseFromParent();
3131 if (CastInst *CI = dyn_cast<CastInst>(I)) {
3132 // If the source of the cast is a constant, then this should have
3133 // already been constant folded. The only reason NOT to constant fold
3134 // it is if something (e.g. LSR) was careful to place the constant
3135 // evaluation in a block other than then one that uses it (e.g. to hoist
3136 // the address of globals out of a loop). If this is the case, we don't
3137 // want to forward-subst the cast.
3138 if (isa<Constant>(CI->getOperand(0)))
3141 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3144 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
3145 /// Sink a zext or sext into its user blocks if the target type doesn't
3146 /// fit in one register
3147 if (TLI && TLI->getTypeAction(CI->getContext(),
3148 TLI->getValueType(CI->getType())) ==
3149 TargetLowering::TypeExpandInteger) {
3150 return SinkCast(CI);
3152 bool MadeChange = MoveExtToFormExtLoad(I);
3153 return MadeChange | OptimizeExtUses(I);
3159 if (CmpInst *CI = dyn_cast<CmpInst>(I))
3160 if (!TLI || !TLI->hasMultipleConditionRegisters())
3161 return OptimizeCmpExpression(CI);
3163 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3165 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3169 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3171 return OptimizeMemoryInst(I, SI->getOperand(1),
3172 SI->getOperand(0)->getType());
3176 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3178 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3179 BinOp->getOpcode() == Instruction::LShr)) {
3180 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3181 if (TLI && CI && TLI->hasExtractBitsInsn())
3182 return OptimizeExtractBits(BinOp, CI, *TLI);
3187 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3188 if (GEPI->hasAllZeroIndices()) {
3189 /// The GEP operand must be a pointer, so must its result -> BitCast
3190 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3191 GEPI->getName(), GEPI);
3192 GEPI->replaceAllUsesWith(NC);
3193 GEPI->eraseFromParent();
3201 if (CallInst *CI = dyn_cast<CallInst>(I))
3202 return OptimizeCallInst(CI);
3204 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3205 return OptimizeSelectInst(SI);
3207 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3208 return OptimizeShuffleVectorInst(SVI);
3213 // In this pass we look for GEP and cast instructions that are used
3214 // across basic blocks and rewrite them to improve basic-block-at-a-time
3216 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
3218 bool MadeChange = false;
3220 CurInstIterator = BB.begin();
3221 while (CurInstIterator != BB.end())
3222 MadeChange |= OptimizeInst(CurInstIterator++);
3224 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3229 // llvm.dbg.value is far away from the value then iSel may not be able
3230 // handle it properly. iSel will drop llvm.dbg.value if it can not
3231 // find a node corresponding to the value.
3232 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3233 bool MadeChange = false;
3234 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3235 Instruction *PrevNonDbgInst = nullptr;
3236 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3237 Instruction *Insn = BI; ++BI;
3238 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3239 // Leave dbg.values that refer to an alloca alone. These
3240 // instrinsics describe the address of a variable (= the alloca)
3241 // being taken. They should not be moved next to the alloca
3242 // (and to the beginning of the scope), but rather stay close to
3243 // where said address is used.
3244 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
3245 PrevNonDbgInst = Insn;
3249 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3250 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3251 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3252 DVI->removeFromParent();
3253 if (isa<PHINode>(VI))
3254 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3256 DVI->insertAfter(VI);
3265 // If there is a sequence that branches based on comparing a single bit
3266 // against zero that can be combined into a single instruction, and the
3267 // target supports folding these into a single instruction, sink the
3268 // mask and compare into the branch uses. Do this before OptimizeBlock ->
3269 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3271 bool CodeGenPrepare::sinkAndCmp(Function &F) {
3272 if (!EnableAndCmpSinking)
3274 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3276 bool MadeChange = false;
3277 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3278 BasicBlock *BB = I++;
3280 // Does this BB end with the following?
3281 // %andVal = and %val, #single-bit-set
3282 // %icmpVal = icmp %andResult, 0
3283 // br i1 %cmpVal label %dest1, label %dest2"
3284 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3285 if (!Brcc || !Brcc->isConditional())
3287 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3288 if (!Cmp || Cmp->getParent() != BB)
3290 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3291 if (!Zero || !Zero->isZero())
3293 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3294 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3296 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3297 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3299 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3301 // Push the "and; icmp" for any users that are conditional branches.
3302 // Since there can only be one branch use per BB, we don't need to keep
3303 // track of which BBs we insert into.
3304 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3308 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3310 if (!BrccUser || !BrccUser->isConditional())
3312 BasicBlock *UserBB = BrccUser->getParent();
3313 if (UserBB == BB) continue;
3314 DEBUG(dbgs() << "found Brcc use\n");
3316 // Sink the "and; icmp" to use.
3318 BinaryOperator *NewAnd =
3319 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3322 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3326 DEBUG(BrccUser->getParent()->dump());