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