Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1 | //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass munges the code in the input function to better prepare it for |
Gordon Henriksen | 829046b | 2008-05-08 17:46:35 +0000 | [diff] [blame] | 11 | // SelectionDAG-based code generation. This works around limitations in it's |
| 12 | // basic-block-at-a-time approach. It should eventually be removed. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Quentin Colombet | a349084 | 2014-02-22 00:07:45 +0000 | [diff] [blame] | 16 | #include "llvm/CodeGen/Passes.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/DenseMap.h" |
| 18 | #include "llvm/ADT/SmallSet.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 21 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 22 | #include "llvm/IR/Constants.h" |
| 23 | #include "llvm/IR/DataLayout.h" |
| 24 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 25 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 26 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 27 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 28 | #include "llvm/IR/IRBuilder.h" |
| 29 | #include "llvm/IR/InlineAsm.h" |
| 30 | #include "llvm/IR/Instructions.h" |
| 31 | #include "llvm/IR/IntrinsicInst.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 32 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 33 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 34 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 35 | #include "llvm/Pass.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 36 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 37 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 38 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 39 | #include "llvm/Target/TargetLibraryInfo.h" |
| 40 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 41 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 42 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 43 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 44 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 46 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 47 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 48 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 49 | #define DEBUG_TYPE "codegenprepare" |
| 50 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 51 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 52 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 53 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 54 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 55 | "sunken Cmps"); |
| 56 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 57 | "of sunken Casts"); |
| 58 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 59 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 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"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 63 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 64 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 65 | STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 66 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 67 | static cl::opt<bool> DisableBranchOpts( |
| 68 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 69 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 70 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 71 | static cl::opt<bool> DisableSelectToBranch( |
| 72 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 73 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 74 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 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.")); |
| 78 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 79 | static cl::opt<bool> EnableAndCmpSinking( |
| 80 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 81 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 82 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 83 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 84 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
| 85 | typedef DenseMap<Instruction *, Type *> InstrToOrigTy; |
| 86 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 87 | class CodeGenPrepare : public FunctionPass { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 88 | /// TLI - Keep a pointer of a TargetLowering to consult for determining |
| 89 | /// transformation profitability. |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 90 | const TargetMachine *TM; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 91 | const TargetLowering *TLI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 92 | const TargetLibraryInfo *TLInfo; |
Cameron Zwarich | 84986b2 | 2011-01-08 17:01:52 +0000 | [diff] [blame] | 93 | DominatorTree *DT; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 94 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 95 | /// CurInstIterator - As we scan instructions optimizing them, this is the |
| 96 | /// next instruction to optimize. Xforms that can invalidate this should |
| 97 | /// update it. |
| 98 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 99 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 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. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 103 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 104 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 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; |
| 110 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 111 | /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 112 | /// be updated. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 113 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 114 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 115 | /// OptSize - True if optimizing for size. |
| 116 | bool OptSize; |
| 117 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 118 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 119 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 120 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
| 121 | : FunctionPass(ID), TM(TM), TLI(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 122 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 123 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 124 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 125 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 126 | const char *getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 127 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 128 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 129 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 130 | AU.addRequired<TargetLibraryInfo>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 131 | } |
| 132 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 133 | private: |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 134 | bool EliminateFallThrough(Function &F); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 135 | bool EliminateMostlyEmptyBlocks(Function &F); |
| 136 | bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 137 | void EliminateMostlyEmptyBlock(BasicBlock *BB); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 138 | bool OptimizeBlock(BasicBlock &BB); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 139 | bool OptimizeInst(Instruction *I); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 140 | bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy); |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 141 | bool OptimizeInlineAsmInst(CallInst *CS); |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 142 | bool OptimizeCallInst(CallInst *CI); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 143 | bool MoveExtToFormExtLoad(Instruction *I); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 144 | bool OptimizeExtUses(Instruction *I); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 145 | bool OptimizeSelectInst(SelectInst *SI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 146 | bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 147 | bool DupRetToEnableTailCallOpts(BasicBlock *BB); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 148 | bool PlaceDbgValues(Function &F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 149 | bool sinkAndCmp(Function &F); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 150 | }; |
| 151 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 152 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 153 | char CodeGenPrepare::ID = 0; |
Jiangning Liu | d623c52 | 2014-06-11 07:04:37 +0000 | [diff] [blame] | 154 | INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare", |
| 155 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 156 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 157 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 158 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 159 | } |
| 160 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 161 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 162 | if (skipOptnoneFunction(F)) |
| 163 | return false; |
| 164 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 165 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 166 | // Clear per function information. |
| 167 | InsertedTruncsSet.clear(); |
| 168 | PromotedInsts.clear(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 169 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 170 | ModifiedDT = false; |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 171 | if (TM) TLI = TM->getTargetLowering(); |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 172 | TLInfo = &getAnalysis<TargetLibraryInfo>(); |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 173 | DominatorTreeWrapperPass *DTWP = |
| 174 | getAnalysisIfAvailable<DominatorTreeWrapperPass>(); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 175 | DT = DTWP ? &DTWP->getDomTree() : nullptr; |
Bill Wendling | 698e84f | 2012-12-30 10:32:01 +0000 | [diff] [blame] | 176 | OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex, |
| 177 | Attribute::OptimizeForSize); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 178 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 179 | /// This optimization identifies DIV instructions that can be |
| 180 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 181 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 182 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 183 | TLI->getBypassSlowDivWidths(); |
Evan Cheng | 71be12b | 2012-09-14 21:25:34 +0000 | [diff] [blame] | 184 | for (Function::iterator I = F.begin(); I != F.end(); I++) |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 185 | EverMadeChange |= bypassSlowDivision(F, I, BypassWidths); |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 186 | } |
| 187 | |
| 188 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 189 | // unconditional branch. |
| 190 | EverMadeChange |= EliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 191 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 192 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 193 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 194 | // find a node corresponding to the value. |
| 195 | EverMadeChange |= PlaceDbgValues(F); |
| 196 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 197 | // If there is a mask, compare against zero, and branch that can be combined |
| 198 | // into a single target instruction, push the mask and compare into branch |
| 199 | // users. Do this before OptimizeBlock -> OptimizeInst -> |
| 200 | // OptimizeCmpExpression, which perturbs the pattern being searched for. |
| 201 | if (!DisableBranchOpts) |
| 202 | EverMadeChange |= sinkAndCmp(F); |
| 203 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 204 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 205 | while (MadeChange) { |
| 206 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 207 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 208 | BasicBlock *BB = I++; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 209 | MadeChange |= OptimizeBlock(*BB); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 210 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 211 | EverMadeChange |= MadeChange; |
| 212 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 213 | |
| 214 | SunkAddrs.clear(); |
| 215 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 216 | if (!DisableBranchOpts) { |
| 217 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 218 | SmallPtrSet<BasicBlock*, 8> WorkList; |
| 219 | for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { |
| 220 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 221 | MadeChange |= ConstantFoldTerminator(BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 222 | if (!MadeChange) continue; |
| 223 | |
| 224 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 225 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 226 | if (pred_begin(*II) == pred_end(*II)) |
| 227 | WorkList.insert(*II); |
| 228 | } |
| 229 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 230 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 231 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 232 | while (!WorkList.empty()) { |
| 233 | BasicBlock *BB = *WorkList.begin(); |
| 234 | WorkList.erase(BB); |
| 235 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 236 | |
| 237 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 238 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 239 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 240 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 241 | if (pred_begin(*II) == pred_end(*II)) |
| 242 | WorkList.insert(*II); |
| 243 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 244 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 245 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 246 | // a single edge. |
| 247 | if (EverMadeChange || MadeChange) |
| 248 | MadeChange |= EliminateFallThrough(F); |
| 249 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 250 | if (MadeChange) |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 251 | ModifiedDT = true; |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 252 | EverMadeChange |= MadeChange; |
| 253 | } |
| 254 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 255 | if (ModifiedDT && DT) |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 256 | DT->recalculate(F); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 257 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 258 | return EverMadeChange; |
| 259 | } |
| 260 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 261 | /// EliminateFallThrough - Merge basic blocks which are connected |
| 262 | /// by a single edge, where one of the basic blocks has a single successor |
| 263 | /// pointing to the other basic block, which has a single predecessor. |
| 264 | bool CodeGenPrepare::EliminateFallThrough(Function &F) { |
| 265 | bool Changed = false; |
| 266 | // Scan all of the blocks in the function, except for the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 267 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 268 | BasicBlock *BB = I++; |
| 269 | // If the destination block has a single pred, then this is a trivial |
| 270 | // edge, just collapse it. |
| 271 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 272 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 273 | // Don't merge if BB's address is taken. |
| 274 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 275 | |
| 276 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 277 | if (Term && !Term->isConditional()) { |
| 278 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 279 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 280 | // Remember if SinglePred was the entry block of the function. |
| 281 | // If so, we will need to move BB back to the entry position. |
| 282 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
| 283 | MergeBasicBlockIntoOnlyPred(BB, this); |
| 284 | |
| 285 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 286 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 287 | |
| 288 | // We have erased a block. Update the iterator. |
| 289 | I = BB; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 290 | } |
| 291 | } |
| 292 | return Changed; |
| 293 | } |
| 294 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 295 | /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes, |
| 296 | /// debug info directives, and an unconditional branch. Passes before isel |
| 297 | /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for |
| 298 | /// isel. Start by eliminating these blocks so we can split them the way we |
| 299 | /// want them. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 300 | bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) { |
| 301 | bool MadeChange = false; |
| 302 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 303 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 304 | BasicBlock *BB = I++; |
| 305 | |
| 306 | // If this block doesn't end with an uncond branch, ignore it. |
| 307 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 308 | if (!BI || !BI->isUnconditional()) |
| 309 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 310 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 311 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 312 | // node, then other stuff is happening here. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 313 | BasicBlock::iterator BBI = BI; |
| 314 | if (BBI != BB->begin()) { |
| 315 | --BBI; |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 316 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 317 | if (BBI == BB->begin()) |
| 318 | break; |
| 319 | --BBI; |
| 320 | } |
| 321 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 322 | continue; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 323 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 324 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 325 | // Do not break infinite loops. |
| 326 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 327 | if (DestBB == BB) |
| 328 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 329 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 330 | if (!CanMergeBlocks(BB, DestBB)) |
| 331 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 332 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 333 | EliminateMostlyEmptyBlock(BB); |
| 334 | MadeChange = true; |
| 335 | } |
| 336 | return MadeChange; |
| 337 | } |
| 338 | |
| 339 | /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a |
| 340 | /// single uncond branch between them, and BB contains no other non-phi |
| 341 | /// instructions. |
| 342 | bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB, |
| 343 | const BasicBlock *DestBB) const { |
| 344 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 345 | // the successor. If there are more complex condition (e.g. preheaders), |
| 346 | // don't mess around with them. |
| 347 | BasicBlock::const_iterator BBI = BB->begin(); |
| 348 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 349 | for (const User *U : PN->users()) { |
| 350 | const Instruction *UI = cast<Instruction>(U); |
| 351 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 352 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 353 | // If User is inside DestBB block and it is a PHINode then check |
| 354 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 355 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 356 | if (UI->getParent() == DestBB) { |
| 357 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 358 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 359 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 360 | if (Insn && Insn->getParent() == BB && |
| 361 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 362 | return false; |
| 363 | } |
| 364 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 365 | } |
| 366 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 367 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 368 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 369 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 370 | // can't merge the block. |
| 371 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 372 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 373 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 374 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 375 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 376 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 377 | // It is faster to get preds from a PHI than with pred_iterator. |
| 378 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 379 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 380 | } else { |
| 381 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 382 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 383 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 384 | // Walk the preds of DestBB. |
| 385 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 386 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 387 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 388 | BBI = DestBB->begin(); |
| 389 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 390 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 391 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 392 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 393 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 394 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 395 | if (V2PN->getParent() == BB) |
| 396 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 397 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 398 | // If there is a conflict, bail out. |
| 399 | if (V1 != V2) return false; |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | return true; |
| 405 | } |
| 406 | |
| 407 | |
| 408 | /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and |
| 409 | /// an unconditional branch in it. |
| 410 | void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) { |
| 411 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 412 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 413 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 414 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 415 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 416 | // If the destination block has a single pred, then this is a trivial edge, |
| 417 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 418 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 419 | if (SinglePred != DestBB) { |
| 420 | // Remember if SinglePred was the entry block of the function. If so, we |
| 421 | // will need to move BB back to the entry position. |
| 422 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 423 | MergeBasicBlockIntoOnlyPred(DestBB, this); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 424 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 425 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 426 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 427 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 428 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 429 | return; |
| 430 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 431 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 432 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 433 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 434 | // to handle the new incoming edges it is about to have. |
| 435 | PHINode *PN; |
| 436 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 437 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 438 | // Remove the incoming value for BB, and remember it. |
| 439 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 440 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 441 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 442 | // value that dominates BB. |
| 443 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 444 | if (InValPhi && InValPhi->getParent() == BB) { |
| 445 | // Add all of the input values of the input PHI as inputs of this phi. |
| 446 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 447 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 448 | InValPhi->getIncomingBlock(i)); |
| 449 | } else { |
| 450 | // Otherwise, add one instance of the dominating value for each edge that |
| 451 | // we will be adding. |
| 452 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 453 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 454 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 455 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 456 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 457 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 458 | } |
| 459 | } |
| 460 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 461 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 462 | // The PHIs are now updated, change everything that refers to BB to use |
| 463 | // DestBB and remove BB. |
| 464 | BB->replaceAllUsesWith(DestBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 465 | if (DT && !ModifiedDT) { |
Cameron Zwarich | 84986b2 | 2011-01-08 17:01:52 +0000 | [diff] [blame] | 466 | BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock(); |
| 467 | BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock(); |
| 468 | BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom); |
| 469 | DT->changeImmediateDominator(DestBB, NewIDom); |
| 470 | DT->eraseNode(BB); |
| 471 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 472 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 473 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 474 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 475 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 476 | } |
| 477 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 478 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 479 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 480 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 481 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 482 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 483 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 484 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 485 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 486 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 487 | UI != E; ) { |
| 488 | Use &TheUse = UI.getUse(); |
| 489 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 490 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 491 | // Figure out which BB this cast is used in. For PHI's this is the |
| 492 | // appropriate predecessor block. |
| 493 | BasicBlock *UserBB = User->getParent(); |
| 494 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 495 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 496 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 497 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 498 | // Preincrement use iterator so we don't invalidate it. |
| 499 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 500 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 501 | // If this user is in the same block as the cast, don't change the cast. |
| 502 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 503 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 504 | // If we have already inserted a cast into this block, use it. |
| 505 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 506 | |
| 507 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 508 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 509 | InsertedCast = |
| 510 | CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 511 | InsertPt); |
| 512 | MadeChange = true; |
| 513 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 514 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 515 | // Replace a use of the cast with a use of the new cast. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 516 | TheUse = InsertedCast; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 517 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 518 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 519 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 520 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 521 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 522 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 523 | MadeChange = true; |
| 524 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 525 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 526 | return MadeChange; |
| 527 | } |
| 528 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 529 | /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop |
| 530 | /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC), |
| 531 | /// sink it into user blocks to reduce the number of virtual |
| 532 | /// registers that must be created and coalesced. |
| 533 | /// |
| 534 | /// Return true if any changes are made. |
| 535 | /// |
| 536 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){ |
| 537 | // If this is a noop copy, |
| 538 | EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType()); |
| 539 | EVT DstVT = TLI.getValueType(CI->getType()); |
| 540 | |
| 541 | // This is an fp<->int conversion? |
| 542 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 543 | return false; |
| 544 | |
| 545 | // If this is an extension, it will be a zero or sign extension, which |
| 546 | // isn't a noop. |
| 547 | if (SrcVT.bitsLT(DstVT)) return false; |
| 548 | |
| 549 | // If these values will be promoted, find out what they will be promoted |
| 550 | // to. This helps us consider truncates on PPC as noop copies when they |
| 551 | // are. |
| 552 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 553 | TargetLowering::TypePromoteInteger) |
| 554 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 555 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 556 | TargetLowering::TypePromoteInteger) |
| 557 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 558 | |
| 559 | // If, after promotion, these are the same types, this is a noop copy. |
| 560 | if (SrcVT != DstVT) |
| 561 | return false; |
| 562 | |
| 563 | return SinkCast(CI); |
| 564 | } |
| 565 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 566 | /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 567 | /// the number of virtual registers that must be created and coalesced. This is |
Chris Lattner | 2740694 | 2007-08-02 16:53:43 +0000 | [diff] [blame] | 568 | /// a clear win except on targets with multiple condition code registers |
| 569 | /// (PowerPC), where it might lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 570 | /// |
| 571 | /// Return true if any changes are made. |
Chris Lattner | 6416a6b | 2008-11-24 22:44:16 +0000 | [diff] [blame] | 572 | static bool OptimizeCmpExpression(CmpInst *CI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 573 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 574 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 575 | /// InsertedCmp - Only insert a cmp in each block once. |
| 576 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 577 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 578 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 579 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 580 | UI != E; ) { |
| 581 | Use &TheUse = UI.getUse(); |
| 582 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 583 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 584 | // Preincrement use iterator so we don't invalidate it. |
| 585 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 586 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 587 | // Don't bother for PHI nodes. |
| 588 | if (isa<PHINode>(User)) |
| 589 | continue; |
| 590 | |
| 591 | // Figure out which BB this cmp is used in. |
| 592 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 593 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 594 | // If this user is in the same block as the cmp, don't change the cmp. |
| 595 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 596 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 597 | // If we have already inserted a cmp into this block, use it. |
| 598 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 599 | |
| 600 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 601 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 602 | InsertedCmp = |
Dan Gohman | ad1f0a1 | 2009-08-25 23:17:54 +0000 | [diff] [blame] | 603 | CmpInst::Create(CI->getOpcode(), |
Owen Anderson | 1e5f00e | 2009-07-09 23:48:35 +0000 | [diff] [blame] | 604 | CI->getPredicate(), CI->getOperand(0), |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 605 | CI->getOperand(1), "", InsertPt); |
| 606 | MadeChange = true; |
| 607 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 608 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 609 | // Replace a use of the cmp with a use of the new cmp. |
| 610 | TheUse = InsertedCmp; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 611 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 612 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 613 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 614 | // If we removed all uses, nuke the cmp. |
| 615 | if (CI->use_empty()) |
| 616 | CI->eraseFromParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 617 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 618 | return MadeChange; |
| 619 | } |
| 620 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 621 | /// isExtractBitsCandidateUse - Check if the candidates could |
| 622 | /// be combined with shift instruction, which includes: |
| 623 | /// 1. Truncate instruction |
| 624 | /// 2. And instruction and the imm is a mask of the low bits: |
| 625 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 626 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 627 | if (!isa<TruncInst>(User)) { |
| 628 | if (User->getOpcode() != Instruction::And || |
| 629 | !isa<ConstantInt>(User->getOperand(1))) |
| 630 | return false; |
| 631 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 632 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 633 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 634 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 635 | return false; |
| 636 | } |
| 637 | return true; |
| 638 | } |
| 639 | |
| 640 | /// SinkShiftAndTruncate - sink both shift and truncate instruction |
| 641 | /// to the use of truncate's BB. |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 642 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 643 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 644 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
| 645 | const TargetLowering &TLI) { |
| 646 | BasicBlock *UserBB = User->getParent(); |
| 647 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 648 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 649 | bool MadeChange = false; |
| 650 | |
| 651 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 652 | TruncE = TruncI->user_end(); |
| 653 | TruncUI != TruncE;) { |
| 654 | |
| 655 | Use &TruncTheUse = TruncUI.getUse(); |
| 656 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 657 | // Preincrement use iterator so we don't invalidate it. |
| 658 | |
| 659 | ++TruncUI; |
| 660 | |
| 661 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 662 | if (!ISDOpcode) |
| 663 | continue; |
| 664 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame^] | 665 | // If the use is actually a legal node, there will not be an |
| 666 | // implicit truncate. |
| 667 | // FIXME: always querying the result type is just an |
| 668 | // approximation; some nodes' legality is determined by the |
| 669 | // operand or other means. There's no good way to find out though. |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 670 | if (TLI.isOperationLegalOrCustom(ISDOpcode, |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame^] | 671 | EVT::getEVT(TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 672 | continue; |
| 673 | |
| 674 | // Don't bother for PHI nodes. |
| 675 | if (isa<PHINode>(TruncUser)) |
| 676 | continue; |
| 677 | |
| 678 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 679 | |
| 680 | if (UserBB == TruncUserBB) |
| 681 | continue; |
| 682 | |
| 683 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 684 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 685 | |
| 686 | if (!InsertedShift && !InsertedTrunc) { |
| 687 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
| 688 | // Sink the shift |
| 689 | if (ShiftI->getOpcode() == Instruction::AShr) |
| 690 | InsertedShift = |
| 691 | BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 692 | else |
| 693 | InsertedShift = |
| 694 | BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 695 | |
| 696 | // Sink the trunc |
| 697 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 698 | TruncInsertPt++; |
| 699 | |
| 700 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
| 701 | TruncI->getType(), "", TruncInsertPt); |
| 702 | |
| 703 | MadeChange = true; |
| 704 | |
| 705 | TruncTheUse = InsertedTrunc; |
| 706 | } |
| 707 | } |
| 708 | return MadeChange; |
| 709 | } |
| 710 | |
| 711 | /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if |
| 712 | /// the uses could potentially be combined with this shift instruction and |
| 713 | /// generate BitExtract instruction. It will only be applied if the architecture |
| 714 | /// supports BitExtract instruction. Here is an example: |
| 715 | /// BB1: |
| 716 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 717 | /// BB2: |
| 718 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 719 | /// ==> |
| 720 | /// |
| 721 | /// BB2: |
| 722 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 723 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 724 | /// |
| 725 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 726 | /// instruction. |
| 727 | /// Return true if any changes are made. |
| 728 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
| 729 | const TargetLowering &TLI) { |
| 730 | BasicBlock *DefBB = ShiftI->getParent(); |
| 731 | |
| 732 | /// Only insert instructions in each block once. |
| 733 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 734 | |
| 735 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType())); |
| 736 | |
| 737 | bool MadeChange = false; |
| 738 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 739 | UI != E;) { |
| 740 | Use &TheUse = UI.getUse(); |
| 741 | Instruction *User = cast<Instruction>(*UI); |
| 742 | // Preincrement use iterator so we don't invalidate it. |
| 743 | ++UI; |
| 744 | |
| 745 | // Don't bother for PHI nodes. |
| 746 | if (isa<PHINode>(User)) |
| 747 | continue; |
| 748 | |
| 749 | if (!isExtractBitsCandidateUse(User)) |
| 750 | continue; |
| 751 | |
| 752 | BasicBlock *UserBB = User->getParent(); |
| 753 | |
| 754 | if (UserBB == DefBB) { |
| 755 | // If the shift and truncate instruction are in the same BB. The use of |
| 756 | // the truncate(TruncUse) may still introduce another truncate if not |
| 757 | // legal. In this case, we would like to sink both shift and truncate |
| 758 | // instruction to the BB of TruncUse. |
| 759 | // for example: |
| 760 | // BB1: |
| 761 | // i64 shift.result = lshr i64 opnd, imm |
| 762 | // trunc.result = trunc shift.result to i16 |
| 763 | // |
| 764 | // BB2: |
| 765 | // ----> We will have an implicit truncate here if the architecture does |
| 766 | // not have i16 compare. |
| 767 | // cmp i16 trunc.result, opnd2 |
| 768 | // |
| 769 | if (isa<TruncInst>(User) && shiftIsLegal |
| 770 | // If the type of the truncate is legal, no trucate will be |
| 771 | // introduced in other basic blocks. |
| 772 | && (!TLI.isTypeLegal(TLI.getValueType(User->getType())))) |
| 773 | MadeChange = |
| 774 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI); |
| 775 | |
| 776 | continue; |
| 777 | } |
| 778 | // If we have already inserted a shift into this block, use it. |
| 779 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 780 | |
| 781 | if (!InsertedShift) { |
| 782 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
| 783 | |
| 784 | if (ShiftI->getOpcode() == Instruction::AShr) |
| 785 | InsertedShift = |
| 786 | BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 787 | else |
| 788 | InsertedShift = |
| 789 | BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 790 | |
| 791 | MadeChange = true; |
| 792 | } |
| 793 | |
| 794 | // Replace a use of the shift with a use of the new shift. |
| 795 | TheUse = InsertedShift; |
| 796 | } |
| 797 | |
| 798 | // If we removed all uses, nuke the shift. |
| 799 | if (ShiftI->use_empty()) |
| 800 | ShiftI->eraseFromParent(); |
| 801 | |
| 802 | return MadeChange; |
| 803 | } |
| 804 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 805 | namespace { |
| 806 | class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls { |
| 807 | protected: |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 808 | void replaceCall(Value *With) override { |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 809 | CI->replaceAllUsesWith(With); |
| 810 | CI->eraseFromParent(); |
| 811 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 812 | bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override { |
Gabor Greif | 6d67395 | 2010-07-16 09:38:02 +0000 | [diff] [blame] | 813 | if (ConstantInt *SizeCI = |
| 814 | dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) |
| 815 | return SizeCI->isAllOnesValue(); |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 816 | return false; |
| 817 | } |
| 818 | }; |
| 819 | } // end anonymous namespace |
| 820 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 821 | bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 822 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 823 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 824 | // Lower inline assembly if we can. |
| 825 | // If we found an inline asm expession, and if the target knows how to |
| 826 | // lower it to normal LLVM code, do so now. |
| 827 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 828 | if (TLI->ExpandInlineAsm(CI)) { |
| 829 | // Avoid invalidating the iterator. |
| 830 | CurInstIterator = BB->begin(); |
| 831 | // Avoid processing instructions out of order, which could cause |
| 832 | // reuse before a value is defined. |
| 833 | SunkAddrs.clear(); |
| 834 | return true; |
| 835 | } |
| 836 | // Sink address computing for memory operands into the block. |
| 837 | if (OptimizeInlineAsmInst(CI)) |
| 838 | return true; |
| 839 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 840 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 841 | // Lower all uses of llvm.objectsize.* |
| 842 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
| 843 | if (II && II->getIntrinsicID() == Intrinsic::objectsize) { |
Gabor Greif | 4a39b84 | 2010-06-24 00:44:01 +0000 | [diff] [blame] | 844 | bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 845 | Type *ReturnTy = CI->getType(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 846 | Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL); |
| 847 | |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 848 | // Substituting this can cause recursive simplifications, which can |
| 849 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 850 | // happens. |
| 851 | WeakVH IterHandle(CurInstIterator); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 852 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 853 | replaceAndRecursivelySimplify(CI, RetVal, |
| 854 | TLI ? TLI->getDataLayout() : nullptr, |
| 855 | TLInfo, ModifiedDT ? nullptr : DT); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 856 | |
| 857 | // If the iterator instruction was recursively deleted, start over at the |
| 858 | // start of the block. |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 859 | if (IterHandle != CurInstIterator) { |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 860 | CurInstIterator = BB->begin(); |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 861 | SunkAddrs.clear(); |
| 862 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 863 | return true; |
| 864 | } |
| 865 | |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 866 | if (II && TLI) { |
| 867 | SmallVector<Value*, 2> PtrOps; |
| 868 | Type *AccessTy; |
| 869 | if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy)) |
| 870 | while (!PtrOps.empty()) |
| 871 | if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy)) |
| 872 | return true; |
| 873 | } |
| 874 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 875 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 876 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 877 | |
Micah Villmow | cdfe20b | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 878 | // We'll need DataLayout from here on out. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 879 | const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 880 | if (!TD) return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 881 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 882 | // Lower all default uses of _chk calls. This is very similar |
| 883 | // to what InstCombineCalls does, but here we are only lowering calls |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 884 | // that have the default "don't know" as the objectsize. Anything else |
| 885 | // should be left alone. |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 886 | CodeGenPrepareFortifiedLibCalls Simplifier; |
Nuno Lopes | 89702e9 | 2012-07-25 16:46:31 +0000 | [diff] [blame] | 887 | return Simplifier.fold(CI, TD, TLInfo); |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 888 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 889 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 890 | /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return |
| 891 | /// instructions to the predecessor to enable tail call optimizations. The |
| 892 | /// case it is currently looking for is: |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 893 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 894 | /// bb0: |
| 895 | /// %tmp0 = tail call i32 @f0() |
| 896 | /// br label %return |
| 897 | /// bb1: |
| 898 | /// %tmp1 = tail call i32 @f1() |
| 899 | /// br label %return |
| 900 | /// bb2: |
| 901 | /// %tmp2 = tail call i32 @f2() |
| 902 | /// br label %return |
| 903 | /// return: |
| 904 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 905 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 906 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 907 | /// |
| 908 | /// => |
| 909 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 910 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 911 | /// bb0: |
| 912 | /// %tmp0 = tail call i32 @f0() |
| 913 | /// ret i32 %tmp0 |
| 914 | /// bb1: |
| 915 | /// %tmp1 = tail call i32 @f1() |
| 916 | /// ret i32 %tmp1 |
| 917 | /// bb2: |
| 918 | /// %tmp2 = tail call i32 @f2() |
| 919 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 920 | /// @endcode |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 921 | bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 922 | if (!TLI) |
| 923 | return false; |
| 924 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 925 | ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 926 | if (!RI) |
| 927 | return false; |
| 928 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 929 | PHINode *PN = nullptr; |
| 930 | BitCastInst *BCI = nullptr; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 931 | Value *V = RI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 932 | if (V) { |
| 933 | BCI = dyn_cast<BitCastInst>(V); |
| 934 | if (BCI) |
| 935 | V = BCI->getOperand(0); |
| 936 | |
| 937 | PN = dyn_cast<PHINode>(V); |
| 938 | if (!PN) |
| 939 | return false; |
| 940 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 941 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 942 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 943 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 944 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 945 | // It's not safe to eliminate the sign / zero extension of the return value. |
| 946 | // See llvm::isInTailCallPosition(). |
| 947 | const Function *F = BB->getParent(); |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 948 | AttributeSet CallerAttrs = F->getAttributes(); |
| 949 | if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || |
| 950 | CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 951 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 952 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 953 | // Make sure there are no instructions between the PHI and return, or that the |
| 954 | // return is the first instruction in the block. |
| 955 | if (PN) { |
| 956 | BasicBlock::iterator BI = BB->begin(); |
| 957 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 958 | if (&*BI == BCI) |
| 959 | // Also skip over the bitcast. |
| 960 | ++BI; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 961 | if (&*BI != RI) |
| 962 | return false; |
| 963 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 964 | BasicBlock::iterator BI = BB->begin(); |
| 965 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
| 966 | if (&*BI != RI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 967 | return false; |
| 968 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 969 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 970 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 971 | /// call. |
| 972 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 973 | if (PN) { |
| 974 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 975 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 976 | // Make sure the phi value is indeed produced by the tail call. |
| 977 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
| 978 | TLI->mayBeEmittedAsTailCall(CI)) |
| 979 | TailCalls.push_back(CI); |
| 980 | } |
| 981 | } else { |
| 982 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 983 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) { |
| 984 | if (!VisitedBBs.insert(*PI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 985 | continue; |
| 986 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 987 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 988 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 989 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 990 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 991 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 992 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 993 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 994 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Cameron Zwarich | 2edfe77 | 2011-03-24 15:54:11 +0000 | [diff] [blame] | 995 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 996 | TailCalls.push_back(CI); |
| 997 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 998 | } |
| 999 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1000 | bool Changed = false; |
| 1001 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 1002 | CallInst *CI = TailCalls[i]; |
| 1003 | CallSite CS(CI); |
| 1004 | |
| 1005 | // Conservatively require the attributes of the call to match those of the |
| 1006 | // return. Ignore noalias because it doesn't affect the call sequence. |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1007 | AttributeSet CalleeAttrs = CS.getAttributes(); |
| 1008 | if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1009 | removeAttribute(Attribute::NoAlias) != |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1010 | AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1011 | removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1012 | continue; |
| 1013 | |
| 1014 | // Make sure the call instruction is followed by an unconditional branch to |
| 1015 | // the return block. |
| 1016 | BasicBlock *CallBB = CI->getParent(); |
| 1017 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 1018 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 1019 | continue; |
| 1020 | |
| 1021 | // Duplicate the return into CallBB. |
| 1022 | (void)FoldReturnIntoUncondBranch(RI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 1023 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1024 | ++NumRetsDup; |
| 1025 | } |
| 1026 | |
| 1027 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 1028 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1029 | BB->eraseFromParent(); |
| 1030 | |
| 1031 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1032 | } |
| 1033 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1034 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1035 | // Memory Optimization |
| 1036 | //===----------------------------------------------------------------------===// |
| 1037 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1038 | namespace { |
| 1039 | |
| 1040 | /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode |
| 1041 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 1042 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1043 | Value *BaseReg; |
| 1044 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1045 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1046 | void print(raw_ostream &OS) const; |
| 1047 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1048 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1049 | bool operator==(const ExtAddrMode& O) const { |
| 1050 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 1051 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 1052 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 1053 | } |
| 1054 | }; |
| 1055 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 1056 | #ifndef NDEBUG |
| 1057 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 1058 | AM.print(OS); |
| 1059 | return OS; |
| 1060 | } |
| 1061 | #endif |
| 1062 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1063 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 1064 | bool NeedPlus = false; |
| 1065 | OS << "["; |
| 1066 | if (BaseGV) { |
| 1067 | OS << (NeedPlus ? " + " : "") |
| 1068 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1069 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1070 | NeedPlus = true; |
| 1071 | } |
| 1072 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 1073 | if (BaseOffs) { |
| 1074 | OS << (NeedPlus ? " + " : "") |
| 1075 | << BaseOffs; |
| 1076 | NeedPlus = true; |
| 1077 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1078 | |
| 1079 | if (BaseReg) { |
| 1080 | OS << (NeedPlus ? " + " : "") |
| 1081 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1082 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1083 | NeedPlus = true; |
| 1084 | } |
| 1085 | if (Scale) { |
| 1086 | OS << (NeedPlus ? " + " : "") |
| 1087 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1088 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1089 | } |
| 1090 | |
| 1091 | OS << ']'; |
| 1092 | } |
| 1093 | |
| 1094 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 1095 | void ExtAddrMode::dump() const { |
| 1096 | print(dbgs()); |
| 1097 | dbgs() << '\n'; |
| 1098 | } |
| 1099 | #endif |
| 1100 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1101 | /// \brief This class provides transaction based operation on the IR. |
| 1102 | /// Every change made through this class is recorded in the internal state and |
| 1103 | /// can be undone (rollback) until commit is called. |
| 1104 | class TypePromotionTransaction { |
| 1105 | |
| 1106 | /// \brief This represents the common interface of the individual transaction. |
| 1107 | /// Each class implements the logic for doing one specific modification on |
| 1108 | /// the IR via the TypePromotionTransaction. |
| 1109 | class TypePromotionAction { |
| 1110 | protected: |
| 1111 | /// The Instruction modified. |
| 1112 | Instruction *Inst; |
| 1113 | |
| 1114 | public: |
| 1115 | /// \brief Constructor of the action. |
| 1116 | /// The constructor performs the related action on the IR. |
| 1117 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 1118 | |
| 1119 | virtual ~TypePromotionAction() {} |
| 1120 | |
| 1121 | /// \brief Undo the modification done by this action. |
| 1122 | /// When this method is called, the IR must be in the same state as it was |
| 1123 | /// before this action was applied. |
| 1124 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 1125 | /// state as it was directly after this action was applied. |
| 1126 | virtual void undo() = 0; |
| 1127 | |
| 1128 | /// \brief Advocate every change made by this action. |
| 1129 | /// When the results on the IR of the action are to be kept, it is important |
| 1130 | /// to call this function, otherwise hidden information may be kept forever. |
| 1131 | virtual void commit() { |
| 1132 | // Nothing to be done, this action is not doing anything. |
| 1133 | } |
| 1134 | }; |
| 1135 | |
| 1136 | /// \brief Utility to remember the position of an instruction. |
| 1137 | class InsertionHandler { |
| 1138 | /// Position of an instruction. |
| 1139 | /// Either an instruction: |
| 1140 | /// - Is the first in a basic block: BB is used. |
| 1141 | /// - Has a previous instructon: PrevInst is used. |
| 1142 | union { |
| 1143 | Instruction *PrevInst; |
| 1144 | BasicBlock *BB; |
| 1145 | } Point; |
| 1146 | /// Remember whether or not the instruction had a previous instruction. |
| 1147 | bool HasPrevInstruction; |
| 1148 | |
| 1149 | public: |
| 1150 | /// \brief Record the position of \p Inst. |
| 1151 | InsertionHandler(Instruction *Inst) { |
| 1152 | BasicBlock::iterator It = Inst; |
| 1153 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 1154 | if (HasPrevInstruction) |
| 1155 | Point.PrevInst = --It; |
| 1156 | else |
| 1157 | Point.BB = Inst->getParent(); |
| 1158 | } |
| 1159 | |
| 1160 | /// \brief Insert \p Inst at the recorded position. |
| 1161 | void insert(Instruction *Inst) { |
| 1162 | if (HasPrevInstruction) { |
| 1163 | if (Inst->getParent()) |
| 1164 | Inst->removeFromParent(); |
| 1165 | Inst->insertAfter(Point.PrevInst); |
| 1166 | } else { |
| 1167 | Instruction *Position = Point.BB->getFirstInsertionPt(); |
| 1168 | if (Inst->getParent()) |
| 1169 | Inst->moveBefore(Position); |
| 1170 | else |
| 1171 | Inst->insertBefore(Position); |
| 1172 | } |
| 1173 | } |
| 1174 | }; |
| 1175 | |
| 1176 | /// \brief Move an instruction before another. |
| 1177 | class InstructionMoveBefore : public TypePromotionAction { |
| 1178 | /// Original position of the instruction. |
| 1179 | InsertionHandler Position; |
| 1180 | |
| 1181 | public: |
| 1182 | /// \brief Move \p Inst before \p Before. |
| 1183 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 1184 | : TypePromotionAction(Inst), Position(Inst) { |
| 1185 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 1186 | Inst->moveBefore(Before); |
| 1187 | } |
| 1188 | |
| 1189 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1190 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1191 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 1192 | Position.insert(Inst); |
| 1193 | } |
| 1194 | }; |
| 1195 | |
| 1196 | /// \brief Set the operand of an instruction with a new value. |
| 1197 | class OperandSetter : public TypePromotionAction { |
| 1198 | /// Original operand of the instruction. |
| 1199 | Value *Origin; |
| 1200 | /// Index of the modified instruction. |
| 1201 | unsigned Idx; |
| 1202 | |
| 1203 | public: |
| 1204 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 1205 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 1206 | : TypePromotionAction(Inst), Idx(Idx) { |
| 1207 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 1208 | << "for:" << *Inst << "\n" |
| 1209 | << "with:" << *NewVal << "\n"); |
| 1210 | Origin = Inst->getOperand(Idx); |
| 1211 | Inst->setOperand(Idx, NewVal); |
| 1212 | } |
| 1213 | |
| 1214 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1215 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1216 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 1217 | << "for: " << *Inst << "\n" |
| 1218 | << "with: " << *Origin << "\n"); |
| 1219 | Inst->setOperand(Idx, Origin); |
| 1220 | } |
| 1221 | }; |
| 1222 | |
| 1223 | /// \brief Hide the operands of an instruction. |
| 1224 | /// Do as if this instruction was not using any of its operands. |
| 1225 | class OperandsHider : public TypePromotionAction { |
| 1226 | /// The list of original operands. |
| 1227 | SmallVector<Value *, 4> OriginalValues; |
| 1228 | |
| 1229 | public: |
| 1230 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 1231 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 1232 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 1233 | unsigned NumOpnds = Inst->getNumOperands(); |
| 1234 | OriginalValues.reserve(NumOpnds); |
| 1235 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 1236 | // Save the current operand. |
| 1237 | Value *Val = Inst->getOperand(It); |
| 1238 | OriginalValues.push_back(Val); |
| 1239 | // Set a dummy one. |
| 1240 | // We could use OperandSetter here, but that would implied an overhead |
| 1241 | // that we are not willing to pay. |
| 1242 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 1243 | } |
| 1244 | } |
| 1245 | |
| 1246 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1247 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1248 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 1249 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 1250 | Inst->setOperand(It, OriginalValues[It]); |
| 1251 | } |
| 1252 | }; |
| 1253 | |
| 1254 | /// \brief Build a truncate instruction. |
| 1255 | class TruncBuilder : public TypePromotionAction { |
| 1256 | public: |
| 1257 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 1258 | /// result. |
| 1259 | /// trunc Opnd to Ty. |
| 1260 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 1261 | IRBuilder<> Builder(Opnd); |
| 1262 | Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted")); |
| 1263 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n"); |
| 1264 | } |
| 1265 | |
| 1266 | /// \brief Get the built instruction. |
| 1267 | Instruction *getBuiltInstruction() { return Inst; } |
| 1268 | |
| 1269 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1270 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1271 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n"); |
| 1272 | Inst->eraseFromParent(); |
| 1273 | } |
| 1274 | }; |
| 1275 | |
| 1276 | /// \brief Build a sign extension instruction. |
| 1277 | class SExtBuilder : public TypePromotionAction { |
| 1278 | public: |
| 1279 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 1280 | /// result. |
| 1281 | /// sext Opnd to Ty. |
| 1282 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
| 1283 | : TypePromotionAction(Inst) { |
| 1284 | IRBuilder<> Builder(InsertPt); |
| 1285 | Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted")); |
| 1286 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n"); |
| 1287 | } |
| 1288 | |
| 1289 | /// \brief Get the built instruction. |
| 1290 | Instruction *getBuiltInstruction() { return Inst; } |
| 1291 | |
| 1292 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1293 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1294 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n"); |
| 1295 | Inst->eraseFromParent(); |
| 1296 | } |
| 1297 | }; |
| 1298 | |
| 1299 | /// \brief Mutate an instruction to another type. |
| 1300 | class TypeMutator : public TypePromotionAction { |
| 1301 | /// Record the original type. |
| 1302 | Type *OrigTy; |
| 1303 | |
| 1304 | public: |
| 1305 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 1306 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 1307 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 1308 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 1309 | << "\n"); |
| 1310 | Inst->mutateType(NewTy); |
| 1311 | } |
| 1312 | |
| 1313 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1314 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1315 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 1316 | << "\n"); |
| 1317 | Inst->mutateType(OrigTy); |
| 1318 | } |
| 1319 | }; |
| 1320 | |
| 1321 | /// \brief Replace the uses of an instruction by another instruction. |
| 1322 | class UsesReplacer : public TypePromotionAction { |
| 1323 | /// Helper structure to keep track of the replaced uses. |
| 1324 | struct InstructionAndIdx { |
| 1325 | /// The instruction using the instruction. |
| 1326 | Instruction *Inst; |
| 1327 | /// The index where this instruction is used for Inst. |
| 1328 | unsigned Idx; |
| 1329 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 1330 | : Inst(Inst), Idx(Idx) {} |
| 1331 | }; |
| 1332 | |
| 1333 | /// Keep track of the original uses (pair Instruction, Index). |
| 1334 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 1335 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 1336 | |
| 1337 | public: |
| 1338 | /// \brief Replace all the use of \p Inst by \p New. |
| 1339 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 1340 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 1341 | << "\n"); |
| 1342 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1343 | for (Use &U : Inst->uses()) { |
| 1344 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 1345 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1346 | } |
| 1347 | // Now, we can replace the uses. |
| 1348 | Inst->replaceAllUsesWith(New); |
| 1349 | } |
| 1350 | |
| 1351 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1352 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1353 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 1354 | for (use_iterator UseIt = OriginalUses.begin(), |
| 1355 | EndIt = OriginalUses.end(); |
| 1356 | UseIt != EndIt; ++UseIt) { |
| 1357 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 1358 | } |
| 1359 | } |
| 1360 | }; |
| 1361 | |
| 1362 | /// \brief Remove an instruction from the IR. |
| 1363 | class InstructionRemover : public TypePromotionAction { |
| 1364 | /// Original position of the instruction. |
| 1365 | InsertionHandler Inserter; |
| 1366 | /// Helper structure to hide all the link to the instruction. In other |
| 1367 | /// words, this helps to do as if the instruction was removed. |
| 1368 | OperandsHider Hider; |
| 1369 | /// Keep track of the uses replaced, if any. |
| 1370 | UsesReplacer *Replacer; |
| 1371 | |
| 1372 | public: |
| 1373 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 1374 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1375 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 1376 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1377 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1378 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1379 | if (New) |
| 1380 | Replacer = new UsesReplacer(Inst, New); |
| 1381 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 1382 | Inst->removeFromParent(); |
| 1383 | } |
| 1384 | |
| 1385 | ~InstructionRemover() { delete Replacer; } |
| 1386 | |
| 1387 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1388 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1389 | |
| 1390 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 1391 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1392 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1393 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 1394 | Inserter.insert(Inst); |
| 1395 | if (Replacer) |
| 1396 | Replacer->undo(); |
| 1397 | Hider.undo(); |
| 1398 | } |
| 1399 | }; |
| 1400 | |
| 1401 | public: |
| 1402 | /// Restoration point. |
| 1403 | /// The restoration point is a pointer to an action instead of an iterator |
| 1404 | /// because the iterator may be invalidated but not the pointer. |
| 1405 | typedef const TypePromotionAction *ConstRestorationPt; |
| 1406 | /// Advocate every changes made in that transaction. |
| 1407 | void commit(); |
| 1408 | /// Undo all the changes made after the given point. |
| 1409 | void rollback(ConstRestorationPt Point); |
| 1410 | /// Get the current restoration point. |
| 1411 | ConstRestorationPt getRestorationPoint() const; |
| 1412 | |
| 1413 | /// \name API for IR modification with state keeping to support rollback. |
| 1414 | /// @{ |
| 1415 | /// Same as Instruction::setOperand. |
| 1416 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 1417 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1418 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1419 | /// Same as Value::replaceAllUsesWith. |
| 1420 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 1421 | /// Same as Value::mutateType. |
| 1422 | void mutateType(Instruction *Inst, Type *NewTy); |
| 1423 | /// Same as IRBuilder::createTrunc. |
| 1424 | Instruction *createTrunc(Instruction *Opnd, Type *Ty); |
| 1425 | /// Same as IRBuilder::createSExt. |
| 1426 | Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
| 1427 | /// Same as Instruction::moveBefore. |
| 1428 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 1429 | /// @} |
| 1430 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1431 | private: |
| 1432 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1433 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 1434 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1435 | }; |
| 1436 | |
| 1437 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 1438 | Value *NewVal) { |
| 1439 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1440 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1441 | } |
| 1442 | |
| 1443 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 1444 | Value *NewVal) { |
| 1445 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1446 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1447 | } |
| 1448 | |
| 1449 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 1450 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1451 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1452 | } |
| 1453 | |
| 1454 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1455 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1456 | } |
| 1457 | |
| 1458 | Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 1459 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1460 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
| 1461 | Instruction *I = Ptr->getBuiltInstruction(); |
| 1462 | Actions.push_back(std::move(Ptr)); |
| 1463 | return I; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1464 | } |
| 1465 | |
| 1466 | Instruction *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 1467 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1468 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
| 1469 | Instruction *I = Ptr->getBuiltInstruction(); |
| 1470 | Actions.push_back(std::move(Ptr)); |
| 1471 | return I; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1472 | } |
| 1473 | |
| 1474 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 1475 | Instruction *Before) { |
| 1476 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1477 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1478 | } |
| 1479 | |
| 1480 | TypePromotionTransaction::ConstRestorationPt |
| 1481 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1482 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1483 | } |
| 1484 | |
| 1485 | void TypePromotionTransaction::commit() { |
| 1486 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1487 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1488 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1489 | Actions.clear(); |
| 1490 | } |
| 1491 | |
| 1492 | void TypePromotionTransaction::rollback( |
| 1493 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1494 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 1495 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1496 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1497 | } |
| 1498 | } |
| 1499 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1500 | /// \brief A helper class for matching addressing modes. |
| 1501 | /// |
| 1502 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 1503 | class AddressingModeMatcher { |
| 1504 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
| 1505 | const TargetLowering &TLI; |
| 1506 | |
| 1507 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 1508 | /// the memory instruction that we're computing this address for. |
| 1509 | Type *AccessTy; |
| 1510 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1511 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1512 | /// AddrMode - This is the addressing mode that we're building up. This is |
| 1513 | /// part of the return value of this addressing mode matching stuff. |
| 1514 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1515 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1516 | /// The truncate instruction inserted by other CodeGenPrepare optimizations. |
| 1517 | const SetOfInstrs &InsertedTruncs; |
| 1518 | /// A map from the instructions to their type before promotion. |
| 1519 | InstrToOrigTy &PromotedInsts; |
| 1520 | /// The ongoing transaction where every action should be registered. |
| 1521 | TypePromotionTransaction &TPT; |
| 1522 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1523 | /// IgnoreProfitability - This is set to true when we should not do |
| 1524 | /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode |
| 1525 | /// always returns true. |
| 1526 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1527 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1528 | AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI, |
| 1529 | const TargetLowering &T, Type *AT, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1530 | Instruction *MI, ExtAddrMode &AM, |
| 1531 | const SetOfInstrs &InsertedTruncs, |
| 1532 | InstrToOrigTy &PromotedInsts, |
| 1533 | TypePromotionTransaction &TPT) |
| 1534 | : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM), |
| 1535 | InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1536 | IgnoreProfitability = false; |
| 1537 | } |
| 1538 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1539 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1540 | /// Match - Find the maximal addressing mode that a load/store of V can fold, |
| 1541 | /// give an access type of AccessTy. This returns a list of involved |
| 1542 | /// instructions in AddrModeInsts. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1543 | /// \p InsertedTruncs The truncate instruction inserted by other |
| 1544 | /// CodeGenPrepare |
| 1545 | /// optimizations. |
| 1546 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1547 | /// \p The ongoing transaction where every action should be registered. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1548 | static ExtAddrMode Match(Value *V, Type *AccessTy, |
| 1549 | Instruction *MemoryInst, |
| 1550 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1551 | const TargetLowering &TLI, |
| 1552 | const SetOfInstrs &InsertedTruncs, |
| 1553 | InstrToOrigTy &PromotedInsts, |
| 1554 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1555 | ExtAddrMode Result; |
| 1556 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1557 | bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy, |
| 1558 | MemoryInst, Result, InsertedTruncs, |
| 1559 | PromotedInsts, TPT).MatchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1560 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 1561 | return Result; |
| 1562 | } |
| 1563 | private: |
| 1564 | bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 1565 | bool MatchAddr(Value *V, unsigned Depth); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1566 | bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1567 | bool *MovedAway = nullptr); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1568 | bool IsProfitableToFoldIntoAddressingMode(Instruction *I, |
| 1569 | ExtAddrMode &AMBefore, |
| 1570 | ExtAddrMode &AMAfter); |
| 1571 | bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 1572 | bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion, |
| 1573 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1574 | }; |
| 1575 | |
| 1576 | /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode. |
| 1577 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 1578 | /// false if not. |
| 1579 | bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale, |
| 1580 | unsigned Depth) { |
| 1581 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 1582 | // mode. Just process that directly. |
| 1583 | if (Scale == 1) |
| 1584 | return MatchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1585 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1586 | // If the scale is 0, it takes nothing to add this. |
| 1587 | if (Scale == 0) |
| 1588 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1589 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1590 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 1591 | // need an available scale field. |
| 1592 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 1593 | return false; |
| 1594 | |
| 1595 | ExtAddrMode TestAddrMode = AddrMode; |
| 1596 | |
| 1597 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 1598 | // [A+B + A*7] -> [B+A*8]. |
| 1599 | TestAddrMode.Scale += Scale; |
| 1600 | TestAddrMode.ScaledReg = ScaleReg; |
| 1601 | |
| 1602 | // If the new address isn't legal, bail out. |
| 1603 | if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) |
| 1604 | return false; |
| 1605 | |
| 1606 | // It was legal, so commit it. |
| 1607 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1608 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1609 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 1610 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 1611 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1612 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1613 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 1614 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 1615 | TestAddrMode.ScaledReg = AddLHS; |
| 1616 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1617 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1618 | // If this addressing mode is legal, commit it and remember that we folded |
| 1619 | // this instruction. |
| 1620 | if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) { |
| 1621 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 1622 | AddrMode = TestAddrMode; |
| 1623 | return true; |
| 1624 | } |
| 1625 | } |
| 1626 | |
| 1627 | // Otherwise, not (x+c)*scale, just return what we have. |
| 1628 | return true; |
| 1629 | } |
| 1630 | |
| 1631 | /// MightBeFoldableInst - This is a little filter, which returns true if an |
| 1632 | /// addressing computation involving I might be folded into a load/store |
| 1633 | /// accessing it. This doesn't need to be perfect, but needs to accept at least |
| 1634 | /// the set of instructions that MatchOperationAddr can. |
| 1635 | static bool MightBeFoldableInst(Instruction *I) { |
| 1636 | switch (I->getOpcode()) { |
| 1637 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 1638 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1639 | // Don't touch identity bitcasts. |
| 1640 | if (I->getType() == I->getOperand(0)->getType()) |
| 1641 | return false; |
| 1642 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 1643 | case Instruction::PtrToInt: |
| 1644 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 1645 | return true; |
| 1646 | case Instruction::IntToPtr: |
| 1647 | // We know the input is intptr_t, so this is foldable. |
| 1648 | return true; |
| 1649 | case Instruction::Add: |
| 1650 | return true; |
| 1651 | case Instruction::Mul: |
| 1652 | case Instruction::Shl: |
| 1653 | // Can only handle X*C and X << C. |
| 1654 | return isa<ConstantInt>(I->getOperand(1)); |
| 1655 | case Instruction::GetElementPtr: |
| 1656 | return true; |
| 1657 | default: |
| 1658 | return false; |
| 1659 | } |
| 1660 | } |
| 1661 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1662 | /// \brief Hepler class to perform type promotion. |
| 1663 | class TypePromotionHelper { |
| 1664 | /// \brief Utility function to check whether or not a sign extension of |
| 1665 | /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either |
| 1666 | /// using the operands of \p Inst or promoting \p Inst. |
| 1667 | /// In other words, check if: |
| 1668 | /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType. |
| 1669 | /// #1 Promotion applies: |
| 1670 | /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...). |
| 1671 | /// #2 Operand reuses: |
| 1672 | /// sext opnd1 to ConsideredSExtType. |
| 1673 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1674 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType, |
| 1675 | const InstrToOrigTy &PromotedInsts); |
| 1676 | |
| 1677 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 1678 | /// promoting \p Inst. |
| 1679 | static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) { |
| 1680 | if (isa<SelectInst>(Inst) && OpIdx == 0) |
| 1681 | return false; |
| 1682 | return true; |
| 1683 | } |
| 1684 | |
| 1685 | /// \brief Utility function to promote the operand of \p SExt when this |
| 1686 | /// operand is a promotable trunc or sext. |
| 1687 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1688 | /// \p CreatedInsts[out] contains how many non-free instructions have been |
| 1689 | /// created to promote the operand of SExt. |
| 1690 | /// Should never be called directly. |
| 1691 | /// \return The promoted value which is used instead of SExt. |
| 1692 | static Value *promoteOperandForTruncAndSExt(Instruction *SExt, |
| 1693 | TypePromotionTransaction &TPT, |
| 1694 | InstrToOrigTy &PromotedInsts, |
| 1695 | unsigned &CreatedInsts); |
| 1696 | |
| 1697 | /// \brief Utility function to promote the operand of \p SExt when this |
| 1698 | /// operand is promotable and is not a supported trunc or sext. |
| 1699 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1700 | /// \p CreatedInsts[out] contains how many non-free instructions have been |
| 1701 | /// created to promote the operand of SExt. |
| 1702 | /// Should never be called directly. |
| 1703 | /// \return The promoted value which is used instead of SExt. |
| 1704 | static Value *promoteOperandForOther(Instruction *SExt, |
| 1705 | TypePromotionTransaction &TPT, |
| 1706 | InstrToOrigTy &PromotedInsts, |
| 1707 | unsigned &CreatedInsts); |
| 1708 | |
| 1709 | public: |
| 1710 | /// Type for the utility function that promotes the operand of SExt. |
| 1711 | typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT, |
| 1712 | InstrToOrigTy &PromotedInsts, |
| 1713 | unsigned &CreatedInsts); |
| 1714 | /// \brief Given a sign extend instruction \p SExt, return the approriate |
| 1715 | /// action to promote the operand of \p SExt instead of using SExt. |
| 1716 | /// \return NULL if no promotable action is possible with the current |
| 1717 | /// sign extension. |
| 1718 | /// \p InsertedTruncs keeps track of all the truncate instructions inserted by |
| 1719 | /// the others CodeGenPrepare optimizations. This information is important |
| 1720 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 1721 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 1722 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1723 | static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs, |
| 1724 | const TargetLowering &TLI, |
| 1725 | const InstrToOrigTy &PromotedInsts); |
| 1726 | }; |
| 1727 | |
| 1728 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
| 1729 | Type *ConsideredSExtType, |
| 1730 | const InstrToOrigTy &PromotedInsts) { |
| 1731 | // We can always get through sext. |
| 1732 | if (isa<SExtInst>(Inst)) |
| 1733 | return true; |
| 1734 | |
| 1735 | // We can get through binary operator, if it is legal. In other words, the |
| 1736 | // binary operator must have a nuw or nsw flag. |
| 1737 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 1738 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
| 1739 | (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap())) |
| 1740 | return true; |
| 1741 | |
| 1742 | // Check if we can do the following simplification. |
| 1743 | // sext(trunc(sext)) --> sext |
| 1744 | if (!isa<TruncInst>(Inst)) |
| 1745 | return false; |
| 1746 | |
| 1747 | Value *OpndVal = Inst->getOperand(0); |
| 1748 | // Check if we can use this operand in the sext. |
| 1749 | // If the type is larger than the result type of the sign extension, |
| 1750 | // we cannot. |
| 1751 | if (OpndVal->getType()->getIntegerBitWidth() > |
| 1752 | ConsideredSExtType->getIntegerBitWidth()) |
| 1753 | return false; |
| 1754 | |
| 1755 | // If the operand of the truncate is not an instruction, we will not have |
| 1756 | // any information on the dropped bits. |
| 1757 | // (Actually we could for constant but it is not worth the extra logic). |
| 1758 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 1759 | if (!Opnd) |
| 1760 | return false; |
| 1761 | |
| 1762 | // Check if the source of the type is narrow enough. |
| 1763 | // I.e., check that trunc just drops sign extended bits. |
| 1764 | // #1 get the type of the operand. |
| 1765 | const Type *OpndType; |
| 1766 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
| 1767 | if (It != PromotedInsts.end()) |
| 1768 | OpndType = It->second; |
| 1769 | else if (isa<SExtInst>(Opnd)) |
| 1770 | OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType(); |
| 1771 | else |
| 1772 | return false; |
| 1773 | |
| 1774 | // #2 check that the truncate just drop sign extended bits. |
| 1775 | if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth()) |
| 1776 | return true; |
| 1777 | |
| 1778 | return false; |
| 1779 | } |
| 1780 | |
| 1781 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
| 1782 | Instruction *SExt, const SetOfInstrs &InsertedTruncs, |
| 1783 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
| 1784 | Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0)); |
| 1785 | Type *SExtTy = SExt->getType(); |
| 1786 | // If the operand of the sign extension is not an instruction, we cannot |
| 1787 | // get through. |
| 1788 | // If it, check we can get through. |
| 1789 | if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1790 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1791 | |
| 1792 | // Do not promote if the operand has been added by codegenprepare. |
| 1793 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 1794 | // redone, thus causing potential infinite loop. |
| 1795 | if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1796 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1797 | |
| 1798 | // SExt or Trunc instructions. |
| 1799 | // Return the related handler. |
| 1800 | if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd)) |
| 1801 | return promoteOperandForTruncAndSExt; |
| 1802 | |
| 1803 | // Regular instruction. |
| 1804 | // Abort early if we will have to insert non-free instructions. |
| 1805 | if (!SExtOpnd->hasOneUse() && |
| 1806 | !TLI.isTruncateFree(SExtTy, SExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1807 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1808 | return promoteOperandForOther; |
| 1809 | } |
| 1810 | |
| 1811 | Value *TypePromotionHelper::promoteOperandForTruncAndSExt( |
| 1812 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
| 1813 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) { |
| 1814 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 1815 | // get through it and this method should not be called. |
| 1816 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
| 1817 | // Replace sext(trunc(opnd)) or sext(sext(opnd)) |
| 1818 | // => sext(opnd). |
| 1819 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 1820 | CreatedInsts = 0; |
| 1821 | |
| 1822 | // Remove dead code. |
| 1823 | if (SExtOpnd->use_empty()) |
| 1824 | TPT.eraseInstruction(SExtOpnd); |
| 1825 | |
| 1826 | // Check if the sext is still needed. |
| 1827 | if (SExt->getType() != SExt->getOperand(0)->getType()) |
| 1828 | return SExt; |
| 1829 | |
| 1830 | // At this point we have: sext ty opnd to ty. |
| 1831 | // Reassign the uses of SExt to the opnd and remove SExt. |
| 1832 | Value *NextVal = SExt->getOperand(0); |
| 1833 | TPT.eraseInstruction(SExt, NextVal); |
| 1834 | return NextVal; |
| 1835 | } |
| 1836 | |
| 1837 | Value * |
| 1838 | TypePromotionHelper::promoteOperandForOther(Instruction *SExt, |
| 1839 | TypePromotionTransaction &TPT, |
| 1840 | InstrToOrigTy &PromotedInsts, |
| 1841 | unsigned &CreatedInsts) { |
| 1842 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 1843 | // get through it and this method should not be called. |
| 1844 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
| 1845 | CreatedInsts = 0; |
| 1846 | if (!SExtOpnd->hasOneUse()) { |
| 1847 | // SExtOpnd will be promoted. |
| 1848 | // All its uses, but SExt, will need to use a truncated value of the |
| 1849 | // promoted version. |
| 1850 | // Create the truncate now. |
| 1851 | Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType()); |
| 1852 | Trunc->removeFromParent(); |
| 1853 | // Insert it just after the definition. |
| 1854 | Trunc->insertAfter(SExtOpnd); |
| 1855 | |
| 1856 | TPT.replaceAllUsesWith(SExtOpnd, Trunc); |
| 1857 | // Restore the operand of SExt (which has been replace by the previous call |
| 1858 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
| 1859 | TPT.setOperand(SExt, 0, SExtOpnd); |
| 1860 | } |
| 1861 | |
| 1862 | // Get through the Instruction: |
| 1863 | // 1. Update its type. |
| 1864 | // 2. Replace the uses of SExt by Inst. |
| 1865 | // 3. Sign extend each operand that needs to be sign extended. |
| 1866 | |
| 1867 | // Remember the original type of the instruction before promotion. |
| 1868 | // This is useful to know that the high bits are sign extended bits. |
| 1869 | PromotedInsts.insert( |
| 1870 | std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType())); |
| 1871 | // Step #1. |
| 1872 | TPT.mutateType(SExtOpnd, SExt->getType()); |
| 1873 | // Step #2. |
| 1874 | TPT.replaceAllUsesWith(SExt, SExtOpnd); |
| 1875 | // Step #3. |
| 1876 | Instruction *SExtForOpnd = SExt; |
| 1877 | |
| 1878 | DEBUG(dbgs() << "Propagate SExt to operands\n"); |
| 1879 | for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
| 1880 | ++OpIdx) { |
| 1881 | DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n'); |
| 1882 | if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() || |
| 1883 | !shouldSExtOperand(SExtOpnd, OpIdx)) { |
| 1884 | DEBUG(dbgs() << "No need to propagate\n"); |
| 1885 | continue; |
| 1886 | } |
| 1887 | // Check if we can statically sign extend the operand. |
| 1888 | Value *Opnd = SExtOpnd->getOperand(OpIdx); |
| 1889 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
| 1890 | DEBUG(dbgs() << "Statically sign extend\n"); |
| 1891 | TPT.setOperand( |
| 1892 | SExtOpnd, OpIdx, |
| 1893 | ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue())); |
| 1894 | continue; |
| 1895 | } |
| 1896 | // UndefValue are typed, so we have to statically sign extend them. |
| 1897 | if (isa<UndefValue>(Opnd)) { |
| 1898 | DEBUG(dbgs() << "Statically sign extend\n"); |
| 1899 | TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType())); |
| 1900 | continue; |
| 1901 | } |
| 1902 | |
| 1903 | // Otherwise we have to explicity sign extend the operand. |
| 1904 | // Check if SExt was reused to sign extend an operand. |
| 1905 | if (!SExtForOpnd) { |
| 1906 | // If yes, create a new one. |
| 1907 | DEBUG(dbgs() << "More operands to sext\n"); |
| 1908 | SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType()); |
| 1909 | ++CreatedInsts; |
| 1910 | } |
| 1911 | |
| 1912 | TPT.setOperand(SExtForOpnd, 0, Opnd); |
| 1913 | |
| 1914 | // Move the sign extension before the insertion point. |
| 1915 | TPT.moveBefore(SExtForOpnd, SExtOpnd); |
| 1916 | TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd); |
| 1917 | // If more sext are required, new instructions will have to be created. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1918 | SExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1919 | } |
| 1920 | if (SExtForOpnd == SExt) { |
| 1921 | DEBUG(dbgs() << "Sign extension is useless now\n"); |
| 1922 | TPT.eraseInstruction(SExt); |
| 1923 | } |
| 1924 | return SExtOpnd; |
| 1925 | } |
| 1926 | |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 1927 | /// IsPromotionProfitable - Check whether or not promoting an instruction |
| 1928 | /// to a wider type was profitable. |
| 1929 | /// \p MatchedSize gives the number of instructions that have been matched |
| 1930 | /// in the addressing mode after the promotion was applied. |
| 1931 | /// \p SizeWithPromotion gives the number of created instructions for |
| 1932 | /// the promotion plus the number of instructions that have been |
| 1933 | /// matched in the addressing mode before the promotion. |
| 1934 | /// \p PromotedOperand is the value that has been promoted. |
| 1935 | /// \return True if the promotion is profitable, false otherwise. |
| 1936 | bool |
| 1937 | AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize, |
| 1938 | unsigned SizeWithPromotion, |
| 1939 | Value *PromotedOperand) const { |
| 1940 | // We folded less instructions than what we created to promote the operand. |
| 1941 | // This is not profitable. |
| 1942 | if (MatchedSize < SizeWithPromotion) |
| 1943 | return false; |
| 1944 | if (MatchedSize > SizeWithPromotion) |
| 1945 | return true; |
| 1946 | // The promotion is neutral but it may help folding the sign extension in |
| 1947 | // loads for instance. |
| 1948 | // Check that we did not create an illegal instruction. |
| 1949 | Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand); |
| 1950 | if (!PromotedInst) |
| 1951 | return false; |
Quentin Colombet | 1627a41 | 2014-02-22 01:06:41 +0000 | [diff] [blame] | 1952 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 1953 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 1954 | if (!ISDOpcode) |
| 1955 | return true; |
| 1956 | // Otherwise, check if the promoted instruction is legal or not. |
| 1957 | return TLI.isOperationLegalOrCustom(ISDOpcode, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 1958 | EVT::getEVT(PromotedInst->getType())); |
| 1959 | } |
| 1960 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1961 | /// MatchOperationAddr - Given an instruction or constant expr, see if we can |
| 1962 | /// fold the operation into the addressing mode. If so, update the addressing |
| 1963 | /// mode and return true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1964 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 1965 | /// not AddrInst has to be folded into the addressing mode on success. |
| 1966 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 1967 | /// because it has been moved away. |
| 1968 | /// Thus AddrInst must not be added in the matched instructions. |
| 1969 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 1970 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 1971 | /// not be referenced anymore. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1972 | bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1973 | unsigned Depth, |
| 1974 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1975 | // Avoid exponential behavior on extremely deep expression trees. |
| 1976 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1977 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1978 | // By default, all matched instructions stay in place. |
| 1979 | if (MovedAway) |
| 1980 | *MovedAway = false; |
| 1981 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1982 | switch (Opcode) { |
| 1983 | case Instruction::PtrToInt: |
| 1984 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 1985 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 1986 | case Instruction::IntToPtr: |
| 1987 | // This inttoptr is a no-op if the integer type is pointer sized. |
| 1988 | if (TLI.getValueType(AddrInst->getOperand(0)->getType()) == |
Matt Arsenault | 37d42ec | 2013-09-06 00:18:43 +0000 | [diff] [blame] | 1989 | TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace())) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1990 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 1991 | return false; |
| 1992 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 1993 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1994 | // BitCast is always a noop, and we can handle it as long as it is |
| 1995 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 1996 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 1997 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 1998 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 1999 | // and we don't want to mess around with them. Assume it knows what it |
| 2000 | // is doing. |
| 2001 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
| 2002 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2003 | return false; |
| 2004 | case Instruction::Add: { |
| 2005 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 2006 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2007 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2008 | // Start a transaction at this point. |
| 2009 | // The LHS may match but not the RHS. |
| 2010 | // Therefore, we need a higher level restoration point to undo partially |
| 2011 | // matched operation. |
| 2012 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2013 | TPT.getRestorationPoint(); |
| 2014 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2015 | if (MatchAddr(AddrInst->getOperand(1), Depth+1) && |
| 2016 | MatchAddr(AddrInst->getOperand(0), Depth+1)) |
| 2017 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2018 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2019 | // Restore the old addr mode info. |
| 2020 | AddrMode = BackupAddrMode; |
| 2021 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2022 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2023 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2024 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. |
| 2025 | if (MatchAddr(AddrInst->getOperand(0), Depth+1) && |
| 2026 | MatchAddr(AddrInst->getOperand(1), Depth+1)) |
| 2027 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2028 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2029 | // Otherwise we definitely can't merge the ADD in. |
| 2030 | AddrMode = BackupAddrMode; |
| 2031 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2032 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2033 | break; |
| 2034 | } |
| 2035 | //case Instruction::Or: |
| 2036 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 2037 | //break; |
| 2038 | case Instruction::Mul: |
| 2039 | case Instruction::Shl: { |
| 2040 | // Can only handle X*C and X << C. |
| 2041 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 2042 | if (!RHS) |
| 2043 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2044 | int64_t Scale = RHS->getSExtValue(); |
| 2045 | if (Opcode == Instruction::Shl) |
| 2046 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2047 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2048 | return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
| 2049 | } |
| 2050 | case Instruction::GetElementPtr: { |
| 2051 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 2052 | // one variable offset. |
| 2053 | int VariableOperand = -1; |
| 2054 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2055 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2056 | int64_t ConstantOffset = 0; |
| 2057 | const DataLayout *TD = TLI.getDataLayout(); |
| 2058 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 2059 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
| 2060 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 2061 | const StructLayout *SL = TD->getStructLayout(STy); |
| 2062 | unsigned Idx = |
| 2063 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 2064 | ConstantOffset += SL->getElementOffset(Idx); |
| 2065 | } else { |
| 2066 | uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType()); |
| 2067 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 2068 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 2069 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 2070 | // We only allow one variable index at the moment. |
| 2071 | if (VariableOperand != -1) |
| 2072 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2073 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2074 | // Remember the variable index. |
| 2075 | VariableOperand = i; |
| 2076 | VariableScale = TypeSize; |
| 2077 | } |
| 2078 | } |
| 2079 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2080 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2081 | // A common case is for the GEP to only do a constant offset. In this case, |
| 2082 | // just add it to the disp field and check validity. |
| 2083 | if (VariableOperand == -1) { |
| 2084 | AddrMode.BaseOffs += ConstantOffset; |
| 2085 | if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){ |
| 2086 | // Check to see if we can fold the base pointer in too. |
| 2087 | if (MatchAddr(AddrInst->getOperand(0), Depth+1)) |
| 2088 | return true; |
| 2089 | } |
| 2090 | AddrMode.BaseOffs -= ConstantOffset; |
| 2091 | return false; |
| 2092 | } |
| 2093 | |
| 2094 | // Save the valid addressing mode in case we can't match. |
| 2095 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2096 | unsigned OldSize = AddrModeInsts.size(); |
| 2097 | |
| 2098 | // See if the scale and offset amount is valid for this target. |
| 2099 | AddrMode.BaseOffs += ConstantOffset; |
| 2100 | |
| 2101 | // Match the base operand of the GEP. |
| 2102 | if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) { |
| 2103 | // If it couldn't be matched, just stuff the value in a register. |
| 2104 | if (AddrMode.HasBaseReg) { |
| 2105 | AddrMode = BackupAddrMode; |
| 2106 | AddrModeInsts.resize(OldSize); |
| 2107 | return false; |
| 2108 | } |
| 2109 | AddrMode.HasBaseReg = true; |
| 2110 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 2111 | } |
| 2112 | |
| 2113 | // Match the remaining variable portion of the GEP. |
| 2114 | if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
| 2115 | Depth)) { |
| 2116 | // If it couldn't be matched, try stuffing the base into a register |
| 2117 | // instead of matching it, and retrying the match of the scale. |
| 2118 | AddrMode = BackupAddrMode; |
| 2119 | AddrModeInsts.resize(OldSize); |
| 2120 | if (AddrMode.HasBaseReg) |
| 2121 | return false; |
| 2122 | AddrMode.HasBaseReg = true; |
| 2123 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 2124 | AddrMode.BaseOffs += ConstantOffset; |
| 2125 | if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), |
| 2126 | VariableScale, Depth)) { |
| 2127 | // If even that didn't work, bail. |
| 2128 | AddrMode = BackupAddrMode; |
| 2129 | AddrModeInsts.resize(OldSize); |
| 2130 | return false; |
| 2131 | } |
| 2132 | } |
| 2133 | |
| 2134 | return true; |
| 2135 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2136 | case Instruction::SExt: { |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 2137 | Instruction *SExt = dyn_cast<Instruction>(AddrInst); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 2138 | if (!SExt) |
| 2139 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 2140 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2141 | // Try to move this sext out of the way of the addressing mode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2142 | // Ask for a method for doing so. |
| 2143 | TypePromotionHelper::Action TPH = TypePromotionHelper::getAction( |
| 2144 | SExt, InsertedTruncs, TLI, PromotedInsts); |
| 2145 | if (!TPH) |
| 2146 | return false; |
| 2147 | |
| 2148 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2149 | TPT.getRestorationPoint(); |
| 2150 | unsigned CreatedInsts = 0; |
| 2151 | Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts); |
| 2152 | // SExt has been moved away. |
| 2153 | // Thus either it will be rematched later in the recursive calls or it is |
| 2154 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 2155 | // E.g., |
| 2156 | // op = add opnd, 1 |
| 2157 | // idx = sext op |
| 2158 | // addr = gep base, idx |
| 2159 | // is now: |
| 2160 | // promotedOpnd = sext opnd <- no match here |
| 2161 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 2162 | // addr = gep base, op <- match |
| 2163 | if (MovedAway) |
| 2164 | *MovedAway = true; |
| 2165 | |
| 2166 | assert(PromotedOperand && |
| 2167 | "TypePromotionHelper should have filtered out those cases"); |
| 2168 | |
| 2169 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2170 | unsigned OldSize = AddrModeInsts.size(); |
| 2171 | |
| 2172 | if (!MatchAddr(PromotedOperand, Depth) || |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2173 | !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts, |
| 2174 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2175 | AddrMode = BackupAddrMode; |
| 2176 | AddrModeInsts.resize(OldSize); |
| 2177 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 2178 | TPT.rollback(LastKnownGood); |
| 2179 | return false; |
| 2180 | } |
| 2181 | return true; |
| 2182 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2183 | } |
| 2184 | return false; |
| 2185 | } |
| 2186 | |
| 2187 | /// MatchAddr - If we can, try to add the value of 'Addr' into the current |
| 2188 | /// addressing mode. If Addr can't be added to AddrMode this returns false and |
| 2189 | /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type |
| 2190 | /// or intptr_t for the target. |
| 2191 | /// |
| 2192 | bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2193 | // Start a transaction at this point that we will rollback if the matching |
| 2194 | // fails. |
| 2195 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2196 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2197 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 2198 | // Fold in immediates if legal for the target. |
| 2199 | AddrMode.BaseOffs += CI->getSExtValue(); |
| 2200 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2201 | return true; |
| 2202 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 2203 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 2204 | // If this is a global variable, try to fold it into the addressing mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2205 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2206 | AddrMode.BaseGV = GV; |
| 2207 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2208 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2209 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2210 | } |
| 2211 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 2212 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2213 | unsigned OldSize = AddrModeInsts.size(); |
| 2214 | |
| 2215 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2216 | bool MovedAway = false; |
| 2217 | if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
| 2218 | // This instruction may have been move away. If so, there is nothing |
| 2219 | // to check here. |
| 2220 | if (MovedAway) |
| 2221 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2222 | // Okay, it's possible to fold this. Check to see if it is actually |
| 2223 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 2224 | // register pressure too much. |
| 2225 | if (I->hasOneUse() || |
| 2226 | IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
| 2227 | AddrModeInsts.push_back(I); |
| 2228 | return true; |
| 2229 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2230 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2231 | // It isn't profitable to do this, roll back. |
| 2232 | //cerr << "NOT FOLDING: " << *I; |
| 2233 | AddrMode = BackupAddrMode; |
| 2234 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2235 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2236 | } |
| 2237 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
| 2238 | if (MatchOperationAddr(CE, CE->getOpcode(), Depth)) |
| 2239 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2240 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2241 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 2242 | // Null pointer gets folded without affecting the addressing mode. |
| 2243 | return true; |
| 2244 | } |
| 2245 | |
| 2246 | // Worse case, the target should support [reg] addressing modes. :) |
| 2247 | if (!AddrMode.HasBaseReg) { |
| 2248 | AddrMode.HasBaseReg = true; |
| 2249 | AddrMode.BaseReg = Addr; |
| 2250 | // Still check for legality in case the target supports [imm] but not [i+r]. |
| 2251 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2252 | return true; |
| 2253 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2254 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2255 | } |
| 2256 | |
| 2257 | // If the base register is already taken, see if we can do [r+r]. |
| 2258 | if (AddrMode.Scale == 0) { |
| 2259 | AddrMode.Scale = 1; |
| 2260 | AddrMode.ScaledReg = Addr; |
| 2261 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2262 | return true; |
| 2263 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2264 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2265 | } |
| 2266 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2267 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2268 | return false; |
| 2269 | } |
| 2270 | |
| 2271 | /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified |
| 2272 | /// inline asm call are due to memory operands. If so, return true, otherwise |
| 2273 | /// return false. |
| 2274 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
| 2275 | const TargetLowering &TLI) { |
| 2276 | TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI)); |
| 2277 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 2278 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2279 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2280 | // Compute the constraint code and ConstraintType to use. |
| 2281 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); |
| 2282 | |
| 2283 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 2284 | // operand, we can't fold it! |
| 2285 | if (OpInfo.CallOperandVal == OpVal && |
| 2286 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 2287 | !OpInfo.isIndirect)) |
| 2288 | return false; |
| 2289 | } |
| 2290 | |
| 2291 | return true; |
| 2292 | } |
| 2293 | |
| 2294 | /// FindAllMemoryUses - Recursively walk all the uses of I until we find a |
| 2295 | /// memory use. If we find an obviously non-foldable instruction, return true. |
| 2296 | /// Add the ultimately found memory instructions to MemoryUses. |
| 2297 | static bool FindAllMemoryUses(Instruction *I, |
| 2298 | SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses, |
| 2299 | SmallPtrSet<Instruction*, 16> &ConsideredInsts, |
| 2300 | const TargetLowering &TLI) { |
| 2301 | // If we already considered this instruction, we're done. |
| 2302 | if (!ConsideredInsts.insert(I)) |
| 2303 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2304 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2305 | // If this is an obviously unfoldable instruction, bail out. |
| 2306 | if (!MightBeFoldableInst(I)) |
| 2307 | return true; |
| 2308 | |
| 2309 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2310 | for (Use &U : I->uses()) { |
| 2311 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2312 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2313 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 2314 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2315 | continue; |
| 2316 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2317 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2318 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 2319 | unsigned opNo = U.getOperandNo(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2320 | if (opNo == 0) return true; // Storing addr, not into addr. |
| 2321 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 2322 | continue; |
| 2323 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2324 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2325 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2326 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 2327 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2328 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2329 | // If this is a memory operand, we're cool, otherwise bail out. |
| 2330 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI)) |
| 2331 | return true; |
| 2332 | continue; |
| 2333 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2334 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2335 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2336 | return true; |
| 2337 | } |
| 2338 | |
| 2339 | return false; |
| 2340 | } |
| 2341 | |
| 2342 | /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at |
| 2343 | /// the use site that we're folding it into. If so, there is no cost to |
| 2344 | /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values |
| 2345 | /// that we know are live at the instruction already. |
| 2346 | bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
| 2347 | Value *KnownLive2) { |
| 2348 | // If Val is either of the known-live values, we know it is live! |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2349 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2350 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2351 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2352 | // All values other than instructions and arguments (e.g. constants) are live. |
| 2353 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2354 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2355 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 2356 | // true because it is just a reference to the stack/frame pointer, which is |
| 2357 | // live for the whole function. |
| 2358 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 2359 | if (AI->isStaticAlloca()) |
| 2360 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2361 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2362 | // Check to see if this value is already used in the memory instruction's |
| 2363 | // block. If so, it's already live into the block at the very least, so we |
| 2364 | // can reasonably fold it. |
| 2365 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 2366 | } |
| 2367 | |
| 2368 | /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing |
| 2369 | /// mode of the machine to fold the specified instruction into a load or store |
| 2370 | /// that ultimately uses it. However, the specified instruction has multiple |
| 2371 | /// uses. Given this, it may actually increase register pressure to fold it |
| 2372 | /// into the load. For example, consider this code: |
| 2373 | /// |
| 2374 | /// X = ... |
| 2375 | /// Y = X+1 |
| 2376 | /// use(Y) -> nonload/store |
| 2377 | /// Z = Y+1 |
| 2378 | /// load Z |
| 2379 | /// |
| 2380 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 2381 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 2382 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 2383 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 2384 | /// number of computations either. |
| 2385 | /// |
| 2386 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 2387 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 2388 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 2389 | bool AddressingModeMatcher:: |
| 2390 | IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
| 2391 | ExtAddrMode &AMAfter) { |
| 2392 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2393 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2394 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 2395 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 2396 | // the set of registers referenced by AMAfter and subtract out those |
| 2397 | // referenced by AMBefore: this is the set of values which folding in this |
| 2398 | // address extends the lifetime of. |
| 2399 | // |
| 2400 | // Note that there are only two potential values being referenced here, |
| 2401 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 2402 | // folded immediates). |
| 2403 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2404 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2405 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 2406 | // lifetime wasn't extended by adding this instruction. |
| 2407 | if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2408 | BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2409 | if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2410 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2411 | |
| 2412 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 2413 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2414 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2415 | return true; |
| 2416 | |
| 2417 | // If all uses of this instruction are ultimately load/store/inlineasm's, |
| 2418 | // check to see if their addressing modes will include this instruction. If |
| 2419 | // so, we can fold it into all uses, so it doesn't matter if it has multiple |
| 2420 | // uses. |
| 2421 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 2422 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
| 2423 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI)) |
| 2424 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2425 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2426 | // Now that we know that all uses of this instruction are part of a chain of |
| 2427 | // computation involving only operations that could theoretically be folded |
| 2428 | // into a memory use, loop over each of these uses and see if they could |
| 2429 | // *actually* fold the instruction. |
| 2430 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 2431 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 2432 | Instruction *User = MemoryUses[i].first; |
| 2433 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2434 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2435 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 2436 | // know what it accesses. |
| 2437 | Value *Address = User->getOperand(OpNo); |
| 2438 | if (!Address->getType()->isPointerTy()) |
| 2439 | return false; |
Matt Arsenault | 8227b9f | 2013-09-06 00:37:24 +0000 | [diff] [blame] | 2440 | Type *AddressAccessTy = Address->getType()->getPointerElementType(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2441 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2442 | // Do a match against the root of this address, ignoring profitability. This |
| 2443 | // will tell us if the addressing mode for the memory operation will |
| 2444 | // *actually* cover the shared instruction. |
| 2445 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 2446 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2447 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2448 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2449 | MemoryInst, Result, InsertedTruncs, |
| 2450 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2451 | Matcher.IgnoreProfitability = true; |
| 2452 | bool Success = Matcher.MatchAddr(Address, 0); |
| 2453 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2454 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 2455 | // The match was to check the profitability, the changes made are not |
| 2456 | // part of the original matcher. Therefore, they should be dropped |
| 2457 | // otherwise the original matcher will not present the right state. |
| 2458 | TPT.rollback(LastKnownGood); |
| 2459 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2460 | // If the match didn't cover I, then it won't be shared by it. |
| 2461 | if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(), |
| 2462 | I) == MatchedAddrModeInsts.end()) |
| 2463 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2464 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2465 | MatchedAddrModeInsts.clear(); |
| 2466 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2467 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2468 | return true; |
| 2469 | } |
| 2470 | |
| 2471 | } // end anonymous namespace |
| 2472 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2473 | /// IsNonLocalValue - Return true if the specified values are defined in a |
| 2474 | /// different basic block than BB. |
| 2475 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 2476 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 2477 | return I->getParent() != BB; |
| 2478 | return false; |
| 2479 | } |
| 2480 | |
Bob Wilson | 53bdae3 | 2009-12-03 21:47:07 +0000 | [diff] [blame] | 2481 | /// OptimizeMemoryInst - Load and Store Instructions often have |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2482 | /// addressing modes that can do significant amounts of computation. As such, |
| 2483 | /// instruction selection will try to get the load or store to do as much |
| 2484 | /// computation as possible for the program. The problem is that isel can only |
| 2485 | /// see within a single block. As such, we sink as much legal addressing mode |
| 2486 | /// stuff into the block as possible. |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2487 | /// |
| 2488 | /// This method is used to optimize both load/store and inline asms with memory |
| 2489 | /// operands. |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 2490 | bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2491 | Type *AccessTy) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2492 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2493 | |
| 2494 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2495 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 2496 | SmallVector<Value*, 8> worklist; |
| 2497 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2498 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2499 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2500 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 2501 | // the addressing mode obtained from the non-PHI roots of the graph |
| 2502 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2503 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2504 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 2505 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2506 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 2507 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2508 | TypePromotionTransaction TPT; |
| 2509 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2510 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2511 | while (!worklist.empty()) { |
| 2512 | Value *V = worklist.back(); |
| 2513 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2514 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2515 | // Break use-def graph loops. |
Nick Lewycky | a3e7ffd | 2011-09-29 23:40:12 +0000 | [diff] [blame] | 2516 | if (!Visited.insert(V)) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2517 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2518 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2519 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2520 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2521 | // For a PHI node, push all of its incoming values. |
| 2522 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
| 2523 | for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) |
| 2524 | worklist.push_back(P->getIncomingValue(i)); |
| 2525 | continue; |
| 2526 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2527 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2528 | // For non-PHIs, determine the addressing mode being computed. |
| 2529 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2530 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
| 2531 | V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet, |
| 2532 | PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 2533 | |
| 2534 | // This check is broken into two cases with very similar code to avoid using |
| 2535 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 2536 | // calling getNumUses() unconditionally caused a significant compile-time |
| 2537 | // regression. |
| 2538 | if (!Consensus) { |
| 2539 | Consensus = V; |
| 2540 | AddrMode = NewAddrMode; |
| 2541 | AddrModeInsts = NewAddrModeInsts; |
| 2542 | continue; |
| 2543 | } else if (NewAddrMode == AddrMode) { |
| 2544 | if (!IsNumUsesConsensusValid) { |
| 2545 | NumUsesConsensus = Consensus->getNumUses(); |
| 2546 | IsNumUsesConsensusValid = true; |
| 2547 | } |
| 2548 | |
| 2549 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 2550 | // for all other roots of the PHI traversal. Also, when choosing one |
| 2551 | // such root as representative, select the one with the most uses in order |
| 2552 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 2553 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2554 | unsigned NumUses = V->getNumUses(); |
| 2555 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2556 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2557 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2558 | AddrModeInsts = NewAddrModeInsts; |
| 2559 | } |
| 2560 | continue; |
| 2561 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2562 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2563 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2564 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2565 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2566 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2567 | // If the addressing mode couldn't be determined, or if multiple different |
| 2568 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2569 | if (!Consensus) { |
| 2570 | TPT.rollback(LastKnownGood); |
| 2571 | return false; |
| 2572 | } |
| 2573 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2574 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2575 | // Check to see if any of the instructions supersumed by this addr mode are |
| 2576 | // non-local to I's BB. |
| 2577 | bool AnyNonLocal = false; |
| 2578 | for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) { |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 2579 | if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) { |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2580 | AnyNonLocal = true; |
| 2581 | break; |
| 2582 | } |
| 2583 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2584 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2585 | // If all the instructions matched are already in this BB, don't do anything. |
| 2586 | if (!AnyNonLocal) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2587 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2588 | return false; |
| 2589 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2590 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2591 | // Insert this computation right after this user. Since our caller is |
| 2592 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 2593 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2594 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2595 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2596 | // Now that we determined the addressing expression we want to use and know |
| 2597 | // that we have to sink it into this block. Check to see if we have already |
| 2598 | // done this for some other load/store instr in this block. If so, reuse the |
| 2599 | // computation. |
| 2600 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 2601 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2602 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2603 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2604 | if (SunkAddr->getType() != Addr->getType()) |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 2605 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2606 | } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() && |
| 2607 | TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) { |
| 2608 | // By default, we use the GEP-based method when AA is used later. This |
| 2609 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 2610 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2611 | << *MemoryInst << "\n"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2612 | Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2613 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2614 | |
| 2615 | // First, find the pointer. |
| 2616 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 2617 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2618 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2619 | } |
| 2620 | |
| 2621 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 2622 | // We can't add more than one pointer together, nor can we scale a |
| 2623 | // pointer (both of which seem meaningless). |
| 2624 | if (ResultPtr || AddrMode.Scale != 1) |
| 2625 | return false; |
| 2626 | |
| 2627 | ResultPtr = AddrMode.ScaledReg; |
| 2628 | AddrMode.Scale = 0; |
| 2629 | } |
| 2630 | |
| 2631 | if (AddrMode.BaseGV) { |
| 2632 | if (ResultPtr) |
| 2633 | return false; |
| 2634 | |
| 2635 | ResultPtr = AddrMode.BaseGV; |
| 2636 | } |
| 2637 | |
| 2638 | // If the real base value actually came from an inttoptr, then the matcher |
| 2639 | // will look through it and provide only the integer value. In that case, |
| 2640 | // use it here. |
| 2641 | if (!ResultPtr && AddrMode.BaseReg) { |
| 2642 | ResultPtr = |
| 2643 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2644 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2645 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 2646 | ResultPtr = |
| 2647 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 2648 | AddrMode.Scale = 0; |
| 2649 | } |
| 2650 | |
| 2651 | if (!ResultPtr && |
| 2652 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 2653 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 2654 | } else if (!ResultPtr) { |
| 2655 | return false; |
| 2656 | } else { |
| 2657 | Type *I8PtrTy = |
| 2658 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 2659 | |
| 2660 | // Start with the base register. Do this first so that subsequent address |
| 2661 | // matching finds it last, which will prevent it from trying to match it |
| 2662 | // as the scaled value in case it happens to be a mul. That would be |
| 2663 | // problematic if we've sunk a different mul for the scale, because then |
| 2664 | // we'd end up sinking both muls. |
| 2665 | if (AddrMode.BaseReg) { |
| 2666 | Value *V = AddrMode.BaseReg; |
| 2667 | if (V->getType() != IntPtrTy) |
| 2668 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 2669 | |
| 2670 | ResultIndex = V; |
| 2671 | } |
| 2672 | |
| 2673 | // Add the scale value. |
| 2674 | if (AddrMode.Scale) { |
| 2675 | Value *V = AddrMode.ScaledReg; |
| 2676 | if (V->getType() == IntPtrTy) { |
| 2677 | // done. |
| 2678 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 2679 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 2680 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 2681 | } else { |
| 2682 | // It is only safe to sign extend the BaseReg if we know that the math |
| 2683 | // required to create it did not overflow before we extend it. Since |
| 2684 | // the original IR value was tossed in favor of a constant back when |
| 2685 | // the AddrMode was created we need to bail out gracefully if widths |
| 2686 | // do not match instead of extending it. |
| 2687 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 2688 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 2689 | I->eraseFromParent(); |
| 2690 | return false; |
| 2691 | } |
| 2692 | |
| 2693 | if (AddrMode.Scale != 1) |
| 2694 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 2695 | "sunkaddr"); |
| 2696 | if (ResultIndex) |
| 2697 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 2698 | else |
| 2699 | ResultIndex = V; |
| 2700 | } |
| 2701 | |
| 2702 | // Add in the Base Offset if present. |
| 2703 | if (AddrMode.BaseOffs) { |
| 2704 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 2705 | if (ResultIndex) { |
| 2706 | // We need to add this separately from the scale above to help with |
| 2707 | // SDAG consecutive load/store merging. |
| 2708 | if (ResultPtr->getType() != I8PtrTy) |
| 2709 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
| 2710 | ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr"); |
| 2711 | } |
| 2712 | |
| 2713 | ResultIndex = V; |
| 2714 | } |
| 2715 | |
| 2716 | if (!ResultIndex) { |
| 2717 | SunkAddr = ResultPtr; |
| 2718 | } else { |
| 2719 | if (ResultPtr->getType() != I8PtrTy) |
| 2720 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
| 2721 | SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr"); |
| 2722 | } |
| 2723 | |
| 2724 | if (SunkAddr->getType() != Addr->getType()) |
| 2725 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
| 2726 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2727 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2728 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2729 | << *MemoryInst << "\n"); |
Matt Arsenault | 37d42ec | 2013-09-06 00:18:43 +0000 | [diff] [blame] | 2730 | Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2731 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2732 | |
| 2733 | // Start with the base register. Do this first so that subsequent address |
| 2734 | // matching finds it last, which will prevent it from trying to match it |
| 2735 | // as the scaled value in case it happens to be a mul. That would be |
| 2736 | // problematic if we've sunk a different mul for the scale, because then |
| 2737 | // we'd end up sinking both muls. |
| 2738 | if (AddrMode.BaseReg) { |
| 2739 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 2740 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2741 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2742 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2743 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2744 | Result = V; |
| 2745 | } |
| 2746 | |
| 2747 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2748 | if (AddrMode.Scale) { |
| 2749 | Value *V = AddrMode.ScaledReg; |
| 2750 | if (V->getType() == IntPtrTy) { |
| 2751 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 2752 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2753 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2754 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 2755 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2756 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2757 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 2758 | // It is only safe to sign extend the BaseReg if we know that the math |
| 2759 | // required to create it did not overflow before we extend it. Since |
| 2760 | // the original IR value was tossed in favor of a constant back when |
| 2761 | // the AddrMode was created we need to bail out gracefully if widths |
| 2762 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 2763 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 2764 | if (I && (Result != AddrMode.BaseReg)) |
| 2765 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 2766 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2767 | } |
| 2768 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2769 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 2770 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2771 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2772 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2773 | else |
| 2774 | Result = V; |
| 2775 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2776 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2777 | // Add in the BaseGV if present. |
| 2778 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2779 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2780 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2781 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2782 | else |
| 2783 | Result = V; |
| 2784 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2785 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2786 | // Add in the Base Offset if present. |
| 2787 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 2788 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2789 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2790 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2791 | else |
| 2792 | Result = V; |
| 2793 | } |
| 2794 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2795 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 2796 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2797 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2798 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2799 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2800 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2801 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2802 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2803 | // If we have no uses, recursively delete the value and all dead instructions |
| 2804 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2805 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2806 | // This can cause recursive deletion, which can invalidate our iterator. |
| 2807 | // Use a WeakVH to hold onto it in case this happens. |
| 2808 | WeakVH IterHandle(CurInstIterator); |
| 2809 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2810 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 2811 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2812 | |
| 2813 | if (IterHandle != CurInstIterator) { |
| 2814 | // If the iterator instruction was recursively deleted, start over at the |
| 2815 | // start of the block. |
| 2816 | CurInstIterator = BB->begin(); |
| 2817 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2818 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 2819 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 2820 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2821 | return true; |
| 2822 | } |
| 2823 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2824 | /// OptimizeInlineAsmInst - If there are any memory operands, use |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2825 | /// OptimizeMemoryInst to sink their address computing into the block when |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2826 | /// possible / profitable. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2827 | bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2828 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2829 | |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2830 | TargetLowering::AsmOperandInfoVector |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2831 | TargetConstraints = TLI->ParseConstraints(CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 2832 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 2833 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 2834 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2835 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2836 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 2837 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2838 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 2839 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 2840 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2841 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 2842 | MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType()); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 2843 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 2844 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2845 | } |
| 2846 | |
| 2847 | return MadeChange; |
| 2848 | } |
| 2849 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2850 | /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same |
| 2851 | /// basic block as the load, unless conditions are unfavorable. This allows |
| 2852 | /// SelectionDAG to fold the extend into the load. |
| 2853 | /// |
| 2854 | bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) { |
| 2855 | // Look for a load being extended. |
| 2856 | LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0)); |
| 2857 | if (!LI) return false; |
| 2858 | |
| 2859 | // If they're already in the same block, there's nothing to do. |
| 2860 | if (LI->getParent() == I->getParent()) |
| 2861 | return false; |
| 2862 | |
| 2863 | // If the load has other users and the truncate is not free, this probably |
| 2864 | // isn't worthwhile. |
| 2865 | if (!LI->hasOneUse() && |
Bob Wilson | b6832a4 | 2010-09-22 18:44:56 +0000 | [diff] [blame] | 2866 | TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) || |
| 2867 | !TLI->isTypeLegal(TLI->getValueType(I->getType()))) && |
Bob Wilson | 4ddcb6a | 2010-09-21 21:54:27 +0000 | [diff] [blame] | 2868 | !TLI->isTruncateFree(I->getType(), LI->getType())) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2869 | return false; |
| 2870 | |
| 2871 | // Check whether the target supports casts folded into loads. |
| 2872 | unsigned LType; |
| 2873 | if (isa<ZExtInst>(I)) |
| 2874 | LType = ISD::ZEXTLOAD; |
| 2875 | else { |
| 2876 | assert(isa<SExtInst>(I) && "Unexpected ext type!"); |
| 2877 | LType = ISD::SEXTLOAD; |
| 2878 | } |
Patrik Hagglund | e98b7a0 | 2012-12-11 11:14:33 +0000 | [diff] [blame] | 2879 | if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType()))) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2880 | return false; |
| 2881 | |
| 2882 | // Move the extend into the same block as the load, so that SelectionDAG |
| 2883 | // can fold it. |
| 2884 | I->removeFromParent(); |
| 2885 | I->insertAfter(LI); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 2886 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2887 | return true; |
| 2888 | } |
| 2889 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2890 | bool CodeGenPrepare::OptimizeExtUses(Instruction *I) { |
| 2891 | BasicBlock *DefBB = I->getParent(); |
| 2892 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 2893 | // If the result of a {s|z}ext and its source are both live out, rewrite all |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2894 | // other uses of the source with result of extension. |
| 2895 | Value *Src = I->getOperand(0); |
| 2896 | if (Src->hasOneUse()) |
| 2897 | return false; |
| 2898 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 2899 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 2900 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 2901 | return false; |
| 2902 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 2903 | // Only safe to perform the optimization if the source is also defined in |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 2904 | // this block. |
| 2905 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 2906 | return false; |
| 2907 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2908 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2909 | for (User *U : I->users()) { |
| 2910 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2911 | |
| 2912 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2913 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2914 | if (UserBB == DefBB) continue; |
| 2915 | DefIsLiveOut = true; |
| 2916 | break; |
| 2917 | } |
| 2918 | if (!DefIsLiveOut) |
| 2919 | return false; |
| 2920 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 2921 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2922 | for (User *U : Src->users()) { |
| 2923 | Instruction *UI = cast<Instruction>(U); |
| 2924 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 2925 | if (UserBB == DefBB) continue; |
| 2926 | // Be conservative. We don't want this xform to end up introducing |
| 2927 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2928 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 2929 | return false; |
| 2930 | } |
| 2931 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2932 | // InsertedTruncs - Only insert one trunc in each block once. |
| 2933 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 2934 | |
| 2935 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2936 | for (Use &U : Src->uses()) { |
| 2937 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2938 | |
| 2939 | // Figure out which BB this ext is used in. |
| 2940 | BasicBlock *UserBB = User->getParent(); |
| 2941 | if (UserBB == DefBB) continue; |
| 2942 | |
| 2943 | // Both src and def are live in this block. Rewrite the use. |
| 2944 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 2945 | |
| 2946 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 2947 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2948 | InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2949 | InsertedTruncsSet.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2950 | } |
| 2951 | |
| 2952 | // Replace a use of the {s|z}ext source with a use of the result. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2953 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 2954 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2955 | MadeChange = true; |
| 2956 | } |
| 2957 | |
| 2958 | return MadeChange; |
| 2959 | } |
| 2960 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 2961 | /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be |
| 2962 | /// turned into an explicit branch. |
| 2963 | static bool isFormingBranchFromSelectProfitable(SelectInst *SI) { |
| 2964 | // FIXME: This should use the same heuristics as IfConversion to determine |
| 2965 | // whether a select is better represented as a branch. This requires that |
| 2966 | // branch probability metadata is preserved for the select, which is not the |
| 2967 | // case currently. |
| 2968 | |
| 2969 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 2970 | |
| 2971 | // If the branch is predicted right, an out of order CPU can avoid blocking on |
| 2972 | // the compare. Emit cmovs on compares with a memory operand as branches to |
| 2973 | // avoid stalls on the load from memory. If the compare has more than one use |
| 2974 | // there's probably another cmov or setcc around so it's not worth emitting a |
| 2975 | // branch. |
| 2976 | if (!Cmp) |
| 2977 | return false; |
| 2978 | |
| 2979 | Value *CmpOp0 = Cmp->getOperand(0); |
| 2980 | Value *CmpOp1 = Cmp->getOperand(1); |
| 2981 | |
| 2982 | // We check that the memory operand has one use to avoid uses of the loaded |
| 2983 | // value directly after the compare, making branches unprofitable. |
| 2984 | return Cmp->hasOneUse() && |
| 2985 | ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) || |
| 2986 | (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse())); |
| 2987 | } |
| 2988 | |
| 2989 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 2990 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 2991 | /// turn it into a branch. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 2992 | bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) { |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 2993 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 2994 | |
| 2995 | // Can we convert the 'select' to CF ? |
| 2996 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 2997 | return false; |
| 2998 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 2999 | TargetLowering::SelectSupportKind SelectKind; |
| 3000 | if (VectorCond) |
| 3001 | SelectKind = TargetLowering::VectorMaskSelect; |
| 3002 | else if (SI->getType()->isVectorTy()) |
| 3003 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 3004 | else |
| 3005 | SelectKind = TargetLowering::ScalarValSelect; |
| 3006 | |
| 3007 | // Do we have efficient codegen support for this kind of 'selects' ? |
| 3008 | if (TLI->isSelectSupported(SelectKind)) { |
| 3009 | // We have efficient codegen support for the select instruction. |
| 3010 | // Check if it is profitable to keep this 'select'. |
| 3011 | if (!TLI->isPredictableSelectExpensive() || |
| 3012 | !isFormingBranchFromSelectProfitable(SI)) |
| 3013 | return false; |
| 3014 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3015 | |
| 3016 | ModifiedDT = true; |
| 3017 | |
| 3018 | // First, we split the block containing the select into 2 blocks. |
| 3019 | BasicBlock *StartBlock = SI->getParent(); |
| 3020 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI)); |
| 3021 | BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
| 3022 | |
| 3023 | // Create a new block serving as the landing pad for the branch. |
| 3024 | BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid", |
| 3025 | NextBlock->getParent(), NextBlock); |
| 3026 | |
| 3027 | // Move the unconditional branch from the block with the select in it into our |
| 3028 | // landing pad block. |
| 3029 | StartBlock->getTerminator()->eraseFromParent(); |
| 3030 | BranchInst::Create(NextBlock, SmallBlock); |
| 3031 | |
| 3032 | // Insert the real conditional branch based on the original condition. |
| 3033 | BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI); |
| 3034 | |
| 3035 | // The select itself is replaced with a PHI Node. |
| 3036 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin()); |
| 3037 | PN->takeName(SI); |
| 3038 | PN->addIncoming(SI->getTrueValue(), StartBlock); |
| 3039 | PN->addIncoming(SI->getFalseValue(), SmallBlock); |
| 3040 | SI->replaceAllUsesWith(PN); |
| 3041 | SI->eraseFromParent(); |
| 3042 | |
| 3043 | // Instruct OptimizeBlock to skip to the next block. |
| 3044 | CurInstIterator = StartBlock->end(); |
| 3045 | ++NumSelectsExpanded; |
| 3046 | return true; |
| 3047 | } |
| 3048 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 3049 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3050 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 3051 | int SplatElem = -1; |
| 3052 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 3053 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 3054 | return false; |
| 3055 | SplatElem = Mask[i]; |
| 3056 | } |
| 3057 | |
| 3058 | return true; |
| 3059 | } |
| 3060 | |
| 3061 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 3062 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 3063 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 3064 | /// codegen can spot all lanes are identical. |
| 3065 | bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
| 3066 | BasicBlock *DefBB = SVI->getParent(); |
| 3067 | |
| 3068 | // Only do this xform if variable vector shifts are particularly expensive. |
| 3069 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 3070 | return false; |
| 3071 | |
| 3072 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 3073 | // constant splat. |
| 3074 | if (!isBroadcastShuffle(SVI)) |
| 3075 | return false; |
| 3076 | |
| 3077 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 3078 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 3079 | |
| 3080 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3081 | for (User *U : SVI->users()) { |
| 3082 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3083 | |
| 3084 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3085 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3086 | if (UserBB == DefBB) continue; |
| 3087 | |
| 3088 | // For now only apply this when the splat is used by a shift instruction. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3089 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3090 | |
| 3091 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 3092 | // already have a copy. |
| 3093 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 3094 | |
| 3095 | if (!InsertedShuffle) { |
| 3096 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
| 3097 | InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0), |
| 3098 | SVI->getOperand(1), |
| 3099 | SVI->getOperand(2), "", InsertPt); |
| 3100 | } |
| 3101 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3102 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3103 | MadeChange = true; |
| 3104 | } |
| 3105 | |
| 3106 | // If we removed all uses, nuke the shuffle. |
| 3107 | if (SVI->use_empty()) { |
| 3108 | SVI->eraseFromParent(); |
| 3109 | MadeChange = true; |
| 3110 | } |
| 3111 | |
| 3112 | return MadeChange; |
| 3113 | } |
| 3114 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3115 | bool CodeGenPrepare::OptimizeInst(Instruction *I) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3116 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 3117 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 3118 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 3119 | // trivial PHI, go ahead and zap it here. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3120 | if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr, |
Benjamin Kramer | 30d249a | 2013-09-24 16:37:40 +0000 | [diff] [blame] | 3121 | TLInfo, DT)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3122 | P->replaceAllUsesWith(V); |
| 3123 | P->eraseFromParent(); |
| 3124 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3125 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3126 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3127 | return false; |
| 3128 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3129 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3130 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3131 | // If the source of the cast is a constant, then this should have |
| 3132 | // already been constant folded. The only reason NOT to constant fold |
| 3133 | // it is if something (e.g. LSR) was careful to place the constant |
| 3134 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 3135 | // the address of globals out of a loop). If this is the case, we don't |
| 3136 | // want to forward-subst the cast. |
| 3137 | if (isa<Constant>(CI->getOperand(0))) |
| 3138 | return false; |
| 3139 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3140 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI)) |
| 3141 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3142 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3143 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 3144 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 3145 | /// fit in one register |
| 3146 | if (TLI && TLI->getTypeAction(CI->getContext(), |
| 3147 | TLI->getValueType(CI->getType())) == |
| 3148 | TargetLowering::TypeExpandInteger) { |
| 3149 | return SinkCast(CI); |
| 3150 | } else { |
| 3151 | bool MadeChange = MoveExtToFormExtLoad(I); |
| 3152 | return MadeChange | OptimizeExtUses(I); |
| 3153 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3154 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3155 | return false; |
| 3156 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3157 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3158 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 3159 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
| 3160 | return OptimizeCmpExpression(CI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3161 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3162 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3163 | if (TLI) |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 3164 | return OptimizeMemoryInst(I, I->getOperand(0), LI->getType()); |
| 3165 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3166 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3167 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3168 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3169 | if (TLI) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3170 | return OptimizeMemoryInst(I, SI->getOperand(1), |
| 3171 | SI->getOperand(0)->getType()); |
| 3172 | return false; |
| 3173 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3174 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 3175 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 3176 | |
| 3177 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 3178 | BinOp->getOpcode() == Instruction::LShr)) { |
| 3179 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 3180 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
| 3181 | return OptimizeExtractBits(BinOp, CI, *TLI); |
| 3182 | |
| 3183 | return false; |
| 3184 | } |
| 3185 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3186 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3187 | if (GEPI->hasAllZeroIndices()) { |
| 3188 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 3189 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 3190 | GEPI->getName(), GEPI); |
| 3191 | GEPI->replaceAllUsesWith(NC); |
| 3192 | GEPI->eraseFromParent(); |
| 3193 | ++NumGEPsElim; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3194 | OptimizeInst(NC); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3195 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3196 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3197 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3198 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3199 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3200 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
| 3201 | return OptimizeCallInst(CI); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3202 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3203 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
| 3204 | return OptimizeSelectInst(SI); |
| 3205 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3206 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
| 3207 | return OptimizeShuffleVectorInst(SVI); |
| 3208 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3209 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3210 | } |
| 3211 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 3212 | // In this pass we look for GEP and cast instructions that are used |
| 3213 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 3214 | // selection. |
| 3215 | bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 3216 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 3217 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3218 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 3219 | CurInstIterator = BB.begin(); |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 3220 | while (CurInstIterator != BB.end()) |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 3221 | MadeChange |= OptimizeInst(CurInstIterator++); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3222 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 3223 | MadeChange |= DupRetToEnableTailCallOpts(&BB); |
| 3224 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 3225 | return MadeChange; |
| 3226 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3227 | |
| 3228 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3229 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3230 | // find a node corresponding to the value. |
| 3231 | bool CodeGenPrepare::PlaceDbgValues(Function &F) { |
| 3232 | bool MadeChange = false; |
| 3233 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3234 | Instruction *PrevNonDbgInst = nullptr; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3235 | for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) { |
| 3236 | Instruction *Insn = BI; ++BI; |
| 3237 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 3238 | // Leave dbg.values that refer to an alloca alone. These |
| 3239 | // instrinsics describe the address of a variable (= the alloca) |
| 3240 | // being taken. They should not be moved next to the alloca |
| 3241 | // (and to the beginning of the scope), but rather stay close to |
| 3242 | // where said address is used. |
| 3243 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3244 | PrevNonDbgInst = Insn; |
| 3245 | continue; |
| 3246 | } |
| 3247 | |
| 3248 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 3249 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
| 3250 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 3251 | DVI->removeFromParent(); |
| 3252 | if (isa<PHINode>(VI)) |
| 3253 | DVI->insertBefore(VI->getParent()->getFirstInsertionPt()); |
| 3254 | else |
| 3255 | DVI->insertAfter(VI); |
| 3256 | MadeChange = true; |
| 3257 | ++NumDbgValueMoved; |
| 3258 | } |
| 3259 | } |
| 3260 | } |
| 3261 | return MadeChange; |
| 3262 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 3263 | |
| 3264 | // If there is a sequence that branches based on comparing a single bit |
| 3265 | // against zero that can be combined into a single instruction, and the |
| 3266 | // target supports folding these into a single instruction, sink the |
| 3267 | // mask and compare into the branch uses. Do this before OptimizeBlock -> |
| 3268 | // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being |
| 3269 | // searched for. |
| 3270 | bool CodeGenPrepare::sinkAndCmp(Function &F) { |
| 3271 | if (!EnableAndCmpSinking) |
| 3272 | return false; |
| 3273 | if (!TLI || !TLI->isMaskAndBranchFoldingLegal()) |
| 3274 | return false; |
| 3275 | bool MadeChange = false; |
| 3276 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ) { |
| 3277 | BasicBlock *BB = I++; |
| 3278 | |
| 3279 | // Does this BB end with the following? |
| 3280 | // %andVal = and %val, #single-bit-set |
| 3281 | // %icmpVal = icmp %andResult, 0 |
| 3282 | // br i1 %cmpVal label %dest1, label %dest2" |
| 3283 | BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator()); |
| 3284 | if (!Brcc || !Brcc->isConditional()) |
| 3285 | continue; |
| 3286 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0)); |
| 3287 | if (!Cmp || Cmp->getParent() != BB) |
| 3288 | continue; |
| 3289 | ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1)); |
| 3290 | if (!Zero || !Zero->isZero()) |
| 3291 | continue; |
| 3292 | Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0)); |
| 3293 | if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB) |
| 3294 | continue; |
| 3295 | ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1)); |
| 3296 | if (!Mask || !Mask->getUniqueInteger().isPowerOf2()) |
| 3297 | continue; |
| 3298 | DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump()); |
| 3299 | |
| 3300 | // Push the "and; icmp" for any users that are conditional branches. |
| 3301 | // Since there can only be one branch use per BB, we don't need to keep |
| 3302 | // track of which BBs we insert into. |
| 3303 | for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end(); |
| 3304 | UI != E; ) { |
| 3305 | Use &TheUse = *UI; |
| 3306 | // Find brcc use. |
| 3307 | BranchInst *BrccUser = dyn_cast<BranchInst>(*UI); |
| 3308 | ++UI; |
| 3309 | if (!BrccUser || !BrccUser->isConditional()) |
| 3310 | continue; |
| 3311 | BasicBlock *UserBB = BrccUser->getParent(); |
| 3312 | if (UserBB == BB) continue; |
| 3313 | DEBUG(dbgs() << "found Brcc use\n"); |
| 3314 | |
| 3315 | // Sink the "and; icmp" to use. |
| 3316 | MadeChange = true; |
| 3317 | BinaryOperator *NewAnd = |
| 3318 | BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "", |
| 3319 | BrccUser); |
| 3320 | CmpInst *NewCmp = |
| 3321 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero, |
| 3322 | "", BrccUser); |
| 3323 | TheUse = NewCmp; |
| 3324 | ++NumAndCmpsMoved; |
| 3325 | DEBUG(BrccUser->getParent()->dump()); |
| 3326 | } |
| 3327 | } |
| 3328 | return MadeChange; |
| 3329 | } |