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