blob: 36d53189604f0780597561a1b8354a728d8202cd [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000021#include "llvm/Analysis/LoopInfo.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000022#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000024#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000025#include "llvm/Analysis/ValueTracking.h"
Petar Jovanovic644b8c12016-04-13 12:25:25 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000027#include "llvm/CodeGen/Analysis.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000032#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000034#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InlineAsm.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000039#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000041#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000042#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000043#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000044#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000045#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000046#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000047#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000050#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
52#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000053#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000054#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000055#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000056using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000057using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000058
Chandler Carruth1b9dde02014-04-22 02:02:50 +000059#define DEBUG_TYPE "codegenprepare"
60
Cameron Zwarichced753f2011-01-05 17:27:27 +000061STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000062STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
63STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000064STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
65 "sunken Cmps");
66STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
67 "of sunken Casts");
68STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
69 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000070STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
71STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000072STATISTIC(NumAndsAdded,
73 "Number of and mask instructions added to form ext loads");
74STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000075STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000076STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000077STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000078STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000079STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000080
Cameron Zwarich338d3622011-03-11 21:52:04 +000081static cl::opt<bool> DisableBranchOpts(
82 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
83 cl::desc("Disable branch optimizations in CodeGenPrepare"));
84
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000085static cl::opt<bool>
86 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
87 cl::desc("Disable GC optimizations in CodeGenPrepare"));
88
Benjamin Kramer3d38c172012-05-06 14:25:16 +000089static cl::opt<bool> DisableSelectToBranch(
90 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
91 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000092
Hal Finkelc3998302014-04-12 00:59:48 +000093static cl::opt<bool> AddrSinkUsingGEPs(
94 "addr-sink-using-gep", cl::Hidden, cl::init(false),
95 cl::desc("Address sinking in CGP using GEPs."));
96
Tim Northovercea0abb2014-03-29 08:22:29 +000097static cl::opt<bool> EnableAndCmpSinking(
98 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
99 cl::desc("Enable sinkinig and/cmp into branches."));
100
Quentin Colombetc32615d2014-10-31 17:52:53 +0000101static cl::opt<bool> DisableStoreExtract(
102 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
103 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
104
105static cl::opt<bool> StressStoreExtract(
106 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
107 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
108
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000109static cl::opt<bool> DisableExtLdPromotion(
110 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
111 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
112 "CodeGenPrepare"));
113
114static cl::opt<bool> StressExtLdPromotion(
115 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
116 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
117 "optimization in CodeGenPrepare"));
118
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000119static cl::opt<bool> DisablePreheaderProtect(
120 "disable-preheader-prot", cl::Hidden, cl::init(false),
121 cl::desc("Disable protection against removing loop preheaders"));
122
Dehao Chen302b69c2016-10-18 20:42:47 +0000123static cl::opt<bool> ProfileGuidedSectionPrefix(
124 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
125 cl::desc("Use profile info to add section prefix for hot/cold functions"));
126
Eric Christopherc1ea1492008-09-24 05:32:41 +0000127namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000128typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000129typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000130typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000131class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000132
Chris Lattner2dd09db2009-09-02 06:11:42 +0000133 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000134 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000135 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000136 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000137 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000138 const LoopInfo *LI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000139
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000140 /// As we scan instructions optimizing them, this is the next instruction
141 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000142 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000143
Evan Cheng0663f232011-03-21 01:19:09 +0000144 /// Keeps track of non-local addresses that have been sunk into a block.
145 /// This allows us to avoid inserting duplicate code for blocks with
146 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000147 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000148
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000149 /// Keeps track of all instructions inserted for the current function.
150 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000151 /// Keeps track of the type of the related instruction before their
152 /// promotion for the current function.
153 InstrToOrigTy PromotedInsts;
154
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000155 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000156 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000157
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000158 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000159 bool OptSize;
160
Mehdi Amini4fe37982015-07-07 18:45:17 +0000161 /// DataLayout for the Function being processed.
162 const DataLayout *DL;
163
Chris Lattnerf2836d12007-03-31 04:06:36 +0000164 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000165 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000166 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000167 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000168 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
169 }
Craig Topper4584cd52014-03-07 09:26:03 +0000170 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000171
Mehdi Amini117296c2016-10-01 02:56:57 +0000172 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000173
Craig Topper4584cd52014-03-07 09:26:03 +0000174 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000175 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000176 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000177 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000178 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000179 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000180 }
181
Chris Lattnerf2836d12007-03-31 04:06:36 +0000182 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000183 bool eliminateFallThrough(Function &F);
184 bool eliminateMostlyEmptyBlocks(Function &F);
185 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
186 void eliminateMostlyEmptyBlock(BasicBlock *BB);
187 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
188 bool optimizeInst(Instruction *I, bool& ModifiedDT);
189 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000190 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000191 bool optimizeInlineAsmInst(CallInst *CS);
192 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
193 bool moveExtToFormExtLoad(Instruction *&I);
194 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000195 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000196 bool optimizeSelectInst(SelectInst *SI);
197 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000198 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000199 bool optimizeExtractElementInst(Instruction *Inst);
200 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
201 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000202 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000203 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000204 Instruction *&Inst,
205 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000206 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000207 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000208 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000209 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000210 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000211}
Devang Patel09f162c2007-05-01 21:15:47 +0000212
Devang Patel8c78a0b2007-05-03 01:11:54 +0000213char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000214INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
215 "Optimize for code generation", false, false)
216INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
217INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
218 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000219
Bill Wendling7a639ea2013-06-19 21:07:11 +0000220FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
221 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000222}
223
Chris Lattnerf2836d12007-03-31 04:06:36 +0000224bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000225 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000226 return false;
227
Mehdi Amini4fe37982015-07-07 18:45:17 +0000228 DL = &F.getParent()->getDataLayout();
229
Chris Lattnerf2836d12007-03-31 04:06:36 +0000230 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000231 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000232 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000233 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000234
Devang Patel8f606d72011-03-24 15:35:25 +0000235 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000236 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000237 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000238 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000239 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000240 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000241 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000242
Dehao Chen302b69c2016-10-18 20:42:47 +0000243 if (ProfileGuidedSectionPrefix) {
244 ProfileSummaryInfo *PSI =
245 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
246 if (PSI->isFunctionEntryHot(&F))
247 F.setSectionPrefix(".hot");
248 else if (PSI->isFunctionEntryCold(&F))
249 F.setSectionPrefix(".cold");
250 }
251
Preston Gurdcdf540d2012-09-04 18:22:17 +0000252 /// This optimization identifies DIV instructions that can be
253 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000254 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000255 const DenseMap<unsigned int, unsigned int> &BypassWidths =
256 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000257 BasicBlock* BB = &*F.begin();
258 while (BB != nullptr) {
259 // bypassSlowDivision may create new BBs, but we don't want to reapply the
260 // optimization to those blocks.
261 BasicBlock* Next = BB->getNextNode();
262 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
263 BB = Next;
264 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000265 }
266
267 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000268 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000269 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000270
Devang Patel53771ba2011-08-18 00:50:51 +0000271 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000272 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000273 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000274 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000275
Tim Northovercea0abb2014-03-29 08:22:29 +0000276 // If there is a mask, compare against zero, and branch that can be combined
277 // into a single target instruction, push the mask and compare into branch
278 // users. Do this before OptimizeBlock -> OptimizeInst ->
279 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000280 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000281 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000282 EverMadeChange |= splitBranchCondition(F);
283 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000284
Chris Lattnerc3748562007-04-02 01:35:34 +0000285 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000286 while (MadeChange) {
287 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000288 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000289 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000290 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000291 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000292
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000293 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000294 if (ModifiedDTOnIteration)
295 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000296 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000297 EverMadeChange |= MadeChange;
298 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000299
300 SunkAddrs.clear();
301
Cameron Zwarich338d3622011-03-11 21:52:04 +0000302 if (!DisableBranchOpts) {
303 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000304 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000305 for (BasicBlock &BB : F) {
306 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
307 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000308 if (!MadeChange) continue;
309
310 for (SmallVectorImpl<BasicBlock*>::iterator
311 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
312 if (pred_begin(*II) == pred_end(*II))
313 WorkList.insert(*II);
314 }
315
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000316 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000317 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000318 while (!WorkList.empty()) {
319 BasicBlock *BB = *WorkList.begin();
320 WorkList.erase(BB);
321 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
322
323 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000324
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000325 for (SmallVectorImpl<BasicBlock*>::iterator
326 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
327 if (pred_begin(*II) == pred_end(*II))
328 WorkList.insert(*II);
329 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000330
Nadav Rotem70409992012-08-14 05:19:07 +0000331 // Merge pairs of basic blocks with unconditional branches, connected by
332 // a single edge.
333 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000334 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000335
Cameron Zwarich338d3622011-03-11 21:52:04 +0000336 EverMadeChange |= MadeChange;
337 }
338
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000339 if (!DisableGCOpts) {
340 SmallVector<Instruction *, 2> Statepoints;
341 for (BasicBlock &BB : F)
342 for (Instruction &I : BB)
343 if (isStatepoint(I))
344 Statepoints.push_back(&I);
345 for (auto &I : Statepoints)
346 EverMadeChange |= simplifyOffsetableRelocate(*I);
347 }
348
Chris Lattnerf2836d12007-03-31 04:06:36 +0000349 return EverMadeChange;
350}
351
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000352/// Merge basic blocks which are connected by a single edge, where one of the
353/// basic blocks has a single successor pointing to the other basic block,
354/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000355bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000356 bool Changed = false;
357 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000358 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000359 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000360 // If the destination block has a single pred, then this is a trivial
361 // edge, just collapse it.
362 BasicBlock *SinglePred = BB->getSinglePredecessor();
363
Evan Cheng64a223a2012-09-28 23:58:57 +0000364 // Don't merge if BB's address is taken.
365 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000366
367 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
368 if (Term && !Term->isConditional()) {
369 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000370 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000371 // Remember if SinglePred was the entry block of the function.
372 // If so, we will need to move BB back to the entry position.
373 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000374 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000375
376 if (isEntry && BB != &BB->getParent()->getEntryBlock())
377 BB->moveBefore(&BB->getParent()->getEntryBlock());
378
379 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000380 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000381 }
382 }
383 return Changed;
384}
385
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000386/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
387/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
388/// edges in ways that are non-optimal for isel. Start by eliminating these
389/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000390bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000391 SmallPtrSet<BasicBlock *, 16> Preheaders;
392 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
393 while (!LoopList.empty()) {
394 Loop *L = LoopList.pop_back_val();
395 LoopList.insert(LoopList.end(), L->begin(), L->end());
396 if (BasicBlock *Preheader = L->getLoopPreheader())
397 Preheaders.insert(Preheader);
398 }
399
Chris Lattnerc3748562007-04-02 01:35:34 +0000400 bool MadeChange = false;
401 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000402 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000403 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000404
405 // If this block doesn't end with an uncond branch, ignore it.
406 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
407 if (!BI || !BI->isUnconditional())
408 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000409
Dale Johannesen4026b042009-03-27 01:13:37 +0000410 // If the instruction before the branch (skipping debug info) isn't a phi
411 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000412 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000413 if (BBI != BB->begin()) {
414 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000415 while (isa<DbgInfoIntrinsic>(BBI)) {
416 if (BBI == BB->begin())
417 break;
418 --BBI;
419 }
420 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
421 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000422 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000423
Chris Lattnerc3748562007-04-02 01:35:34 +0000424 // Do not break infinite loops.
425 BasicBlock *DestBB = BI->getSuccessor(0);
426 if (DestBB == BB)
427 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000428
Sanjay Patelfc580a62015-09-21 23:03:16 +0000429 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000430 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000431
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000432 // Do not delete loop preheaders if doing so would create a critical edge.
433 // Loop preheaders can be good locations to spill registers. If the
434 // preheader is deleted and we create a critical edge, registers may be
435 // spilled in the loop body instead.
436 if (!DisablePreheaderProtect && Preheaders.count(BB) &&
437 !(BB->getSinglePredecessor() && BB->getSinglePredecessor()->getSingleSuccessor()))
438 continue;
439
Sanjay Patelfc580a62015-09-21 23:03:16 +0000440 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000441 MadeChange = true;
442 }
443 return MadeChange;
444}
445
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000446/// Return true if we can merge BB into DestBB if there is a single
447/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000448/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000449bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000450 const BasicBlock *DestBB) const {
451 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
452 // the successor. If there are more complex condition (e.g. preheaders),
453 // don't mess around with them.
454 BasicBlock::const_iterator BBI = BB->begin();
455 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000456 for (const User *U : PN->users()) {
457 const Instruction *UI = cast<Instruction>(U);
458 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000459 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000460 // If User is inside DestBB block and it is a PHINode then check
461 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000462 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000463 if (UI->getParent() == DestBB) {
464 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000465 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
466 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
467 if (Insn && Insn->getParent() == BB &&
468 Insn->getParent() != UPN->getIncomingBlock(I))
469 return false;
470 }
471 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000472 }
473 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000474
Chris Lattnerc3748562007-04-02 01:35:34 +0000475 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
476 // and DestBB may have conflicting incoming values for the block. If so, we
477 // can't merge the block.
478 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
479 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000480
Chris Lattnerc3748562007-04-02 01:35:34 +0000481 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000482 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000483 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
484 // It is faster to get preds from a PHI than with pred_iterator.
485 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
486 BBPreds.insert(BBPN->getIncomingBlock(i));
487 } else {
488 BBPreds.insert(pred_begin(BB), pred_end(BB));
489 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000490
Chris Lattnerc3748562007-04-02 01:35:34 +0000491 // Walk the preds of DestBB.
492 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
493 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
494 if (BBPreds.count(Pred)) { // Common predecessor?
495 BBI = DestBB->begin();
496 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
497 const Value *V1 = PN->getIncomingValueForBlock(Pred);
498 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000499
Chris Lattnerc3748562007-04-02 01:35:34 +0000500 // If V2 is a phi node in BB, look up what the mapped value will be.
501 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
502 if (V2PN->getParent() == BB)
503 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000504
Chris Lattnerc3748562007-04-02 01:35:34 +0000505 // If there is a conflict, bail out.
506 if (V1 != V2) return false;
507 }
508 }
509 }
510
511 return true;
512}
513
514
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000515/// Eliminate a basic block that has only phi's and an unconditional branch in
516/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000517void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000518 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
519 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000520
David Greene74e2d492010-01-05 01:27:11 +0000521 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000522
Chris Lattnerc3748562007-04-02 01:35:34 +0000523 // If the destination block has a single pred, then this is a trivial edge,
524 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000525 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000526 if (SinglePred != DestBB) {
527 // Remember if SinglePred was the entry block of the function. If so, we
528 // will need to move BB back to the entry position.
529 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000530 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000531
Chris Lattner8a172da2008-11-28 19:54:49 +0000532 if (isEntry && BB != &BB->getParent()->getEntryBlock())
533 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000534
David Greene74e2d492010-01-05 01:27:11 +0000535 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000536 return;
537 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000538 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000539
Chris Lattnerc3748562007-04-02 01:35:34 +0000540 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
541 // to handle the new incoming edges it is about to have.
542 PHINode *PN;
543 for (BasicBlock::iterator BBI = DestBB->begin();
544 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
545 // Remove the incoming value for BB, and remember it.
546 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000547
Chris Lattnerc3748562007-04-02 01:35:34 +0000548 // Two options: either the InVal is a phi node defined in BB or it is some
549 // value that dominates BB.
550 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
551 if (InValPhi && InValPhi->getParent() == BB) {
552 // Add all of the input values of the input PHI as inputs of this phi.
553 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
554 PN->addIncoming(InValPhi->getIncomingValue(i),
555 InValPhi->getIncomingBlock(i));
556 } else {
557 // Otherwise, add one instance of the dominating value for each edge that
558 // we will be adding.
559 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
560 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
561 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
562 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000563 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
564 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000565 }
566 }
567 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000568
Chris Lattnerc3748562007-04-02 01:35:34 +0000569 // The PHIs are now updated, change everything that refers to BB to use
570 // DestBB and remove BB.
571 BB->replaceAllUsesWith(DestBB);
572 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000573 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000574
David Greene74e2d492010-01-05 01:27:11 +0000575 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000576}
577
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000578// Computes a map of base pointer relocation instructions to corresponding
579// derived pointer relocation instructions given a vector of all relocate calls
580static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000581 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
582 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
583 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000584 // Collect information in two maps: one primarily for locating the base object
585 // while filling the second map; the second map is the final structure holding
586 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000587 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
588 for (auto *ThisRelocate : AllRelocateCalls) {
589 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
590 ThisRelocate->getDerivedPtrIndex());
591 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000592 }
593 for (auto &Item : RelocateIdxMap) {
594 std::pair<unsigned, unsigned> Key = Item.first;
595 if (Key.first == Key.second)
596 // Base relocation: nothing to insert
597 continue;
598
Manuel Jacob83eefa62016-01-05 04:03:00 +0000599 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000600 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000601
602 // We're iterating over RelocateIdxMap so we cannot modify it.
603 auto MaybeBase = RelocateIdxMap.find(BaseKey);
604 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000605 // TODO: We might want to insert a new base object relocate and gep off
606 // that, if there are enough derived object relocates.
607 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000608
609 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000610 }
611}
612
613// Accepts a GEP and extracts the operands into a vector provided they're all
614// small integer constants
615static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
616 SmallVectorImpl<Value *> &OffsetV) {
617 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
618 // Only accept small constant integer operands
619 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
620 if (!Op || Op->getZExtValue() > 20)
621 return false;
622 }
623
624 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
625 OffsetV.push_back(GEP->getOperand(i));
626 return true;
627}
628
629// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
630// replace, computes a replacement, and affects it.
631static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000632simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
633 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000634 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000635 for (GCRelocateInst *ToReplace : Targets) {
636 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000637 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000638 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000639 // A duplicate relocate call. TODO: coalesce duplicates.
640 continue;
641 }
642
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000643 if (RelocatedBase->getParent() != ToReplace->getParent()) {
644 // Base and derived relocates are in different basic blocks.
645 // In this case transform is only valid when base dominates derived
646 // relocate. However it would be too expensive to check dominance
647 // for each such relocate, so we skip the whole transformation.
648 continue;
649 }
650
Manuel Jacob83eefa62016-01-05 04:03:00 +0000651 Value *Base = ToReplace->getBasePtr();
652 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000653 if (!Derived || Derived->getPointerOperand() != Base)
654 continue;
655
656 SmallVector<Value *, 2> OffsetV;
657 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
658 continue;
659
660 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000661 assert(RelocatedBase->getNextNode() &&
662 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000663
664 // Insert after RelocatedBase
665 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000666 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000667
668 // If gc_relocate does not match the actual type, cast it to the right type.
669 // In theory, there must be a bitcast after gc_relocate if the type does not
670 // match, and we should reuse it to get the derived pointer. But it could be
671 // cases like this:
672 // bb1:
673 // ...
674 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
675 // br label %merge
676 //
677 // bb2:
678 // ...
679 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
680 // br label %merge
681 //
682 // merge:
683 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
684 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
685 //
686 // In this case, we can not find the bitcast any more. So we insert a new bitcast
687 // no matter there is already one or not. In this way, we can handle all cases, and
688 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000689 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000690 if (RelocatedBase->getType() != Base->getType()) {
691 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000692 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000693 }
David Blaikie68d535c2015-03-24 22:38:16 +0000694 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000695 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000696 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000697 // If the newly generated derived pointer's type does not match the original derived
698 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000699 Value *ActualReplacement = Replacement;
700 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000701 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000702 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000703 }
704 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000705 ToReplace->eraseFromParent();
706
707 MadeChange = true;
708 }
709 return MadeChange;
710}
711
712// Turns this:
713//
714// %base = ...
715// %ptr = gep %base + 15
716// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
717// %base' = relocate(%tok, i32 4, i32 4)
718// %ptr' = relocate(%tok, i32 4, i32 5)
719// %val = load %ptr'
720//
721// into this:
722//
723// %base = ...
724// %ptr = gep %base + 15
725// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
726// %base' = gc.relocate(%tok, i32 4, i32 4)
727// %ptr' = gep %base' + 15
728// %val = load %ptr'
729bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
730 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000731 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000732
733 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000734 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000735 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000736 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000737
738 // We need atleast one base pointer relocation + one derived pointer
739 // relocation to mangle
740 if (AllRelocateCalls.size() < 2)
741 return false;
742
743 // RelocateInstMap is a mapping from the base relocate instruction to the
744 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000745 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000746 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
747 if (RelocateInstMap.empty())
748 return false;
749
750 for (auto &Item : RelocateInstMap)
751 // Item.first is the RelocatedBase to offset against
752 // Item.second is the vector of Targets to replace
753 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
754 return MadeChange;
755}
756
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000757/// SinkCast - Sink the specified cast instruction into its user blocks
758static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000759 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000760
Chris Lattnerf2836d12007-03-31 04:06:36 +0000761 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000762 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000763
Chris Lattnerf2836d12007-03-31 04:06:36 +0000764 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000765 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000766 UI != E; ) {
767 Use &TheUse = UI.getUse();
768 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000769
Chris Lattnerf2836d12007-03-31 04:06:36 +0000770 // Figure out which BB this cast is used in. For PHI's this is the
771 // appropriate predecessor block.
772 BasicBlock *UserBB = User->getParent();
773 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000774 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000775 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000776
Chris Lattnerf2836d12007-03-31 04:06:36 +0000777 // Preincrement use iterator so we don't invalidate it.
778 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000779
David Majnemer0c80e2e2016-04-27 19:36:38 +0000780 // The first insertion point of a block containing an EH pad is after the
781 // pad. If the pad is the user, we cannot sink the cast past the pad.
782 if (User->isEHPad())
783 continue;
784
Andrew Kaylord0430e82015-11-23 19:16:15 +0000785 // If the block selected to receive the cast is an EH pad that does not
786 // allow non-PHI instructions before the terminator, we can't sink the
787 // cast.
788 if (UserBB->getTerminator()->isEHPad())
789 continue;
790
Chris Lattnerf2836d12007-03-31 04:06:36 +0000791 // If this user is in the same block as the cast, don't change the cast.
792 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000793
Chris Lattnerf2836d12007-03-31 04:06:36 +0000794 // If we have already inserted a cast into this block, use it.
795 CastInst *&InsertedCast = InsertedCasts[UserBB];
796
797 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000798 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000799 assert(InsertPt != UserBB->end());
800 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
801 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000802 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000803
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000804 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000805 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000806 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000807 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000808 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000809
Chris Lattnerf2836d12007-03-31 04:06:36 +0000810 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000811 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000812 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000813 MadeChange = true;
814 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000815
Chris Lattnerf2836d12007-03-31 04:06:36 +0000816 return MadeChange;
817}
818
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000819/// If the specified cast instruction is a noop copy (e.g. it's casting from
820/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
821/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000822///
823/// Return true if any changes are made.
824///
Mehdi Amini44ede332015-07-09 02:09:04 +0000825static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
826 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000827 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000828 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
829 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000830
831 // This is an fp<->int conversion?
832 if (SrcVT.isInteger() != DstVT.isInteger())
833 return false;
834
835 // If this is an extension, it will be a zero or sign extension, which
836 // isn't a noop.
837 if (SrcVT.bitsLT(DstVT)) return false;
838
839 // If these values will be promoted, find out what they will be promoted
840 // to. This helps us consider truncates on PPC as noop copies when they
841 // are.
842 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
843 TargetLowering::TypePromoteInteger)
844 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
845 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
846 TargetLowering::TypePromoteInteger)
847 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
848
849 // If, after promotion, these are the same types, this is a noop copy.
850 if (SrcVT != DstVT)
851 return false;
852
853 return SinkCast(CI);
854}
855
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000856/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
857/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000858///
859/// Return true if any changes were made.
860static bool CombineUAddWithOverflow(CmpInst *CI) {
861 Value *A, *B;
862 Instruction *AddI;
863 if (!match(CI,
864 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
865 return false;
866
867 Type *Ty = AddI->getType();
868 if (!isa<IntegerType>(Ty))
869 return false;
870
871 // We don't want to move around uses of condition values this late, so we we
872 // check if it is legal to create the call to the intrinsic in the basic
873 // block containing the icmp:
874
875 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
876 return false;
877
878#ifndef NDEBUG
879 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
880 // for now:
881 if (AddI->hasOneUse())
882 assert(*AddI->user_begin() == CI && "expected!");
883#endif
884
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000885 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000886 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
887
888 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
889
890 auto *UAddWithOverflow =
891 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
892 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
893 auto *Overflow =
894 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
895
896 CI->replaceAllUsesWith(Overflow);
897 AddI->replaceAllUsesWith(UAdd);
898 CI->eraseFromParent();
899 AddI->eraseFromParent();
900 return true;
901}
902
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000903/// Sink the given CmpInst into user blocks to reduce the number of virtual
904/// registers that must be created and coalesced. This is a clear win except on
905/// targets with multiple condition code registers (PowerPC), where it might
906/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000907///
908/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000909static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000910 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000911
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000912 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000913 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000914 return false;
915
916 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000917 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000918
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000919 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000920 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000921 UI != E; ) {
922 Use &TheUse = UI.getUse();
923 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000924
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000925 // Preincrement use iterator so we don't invalidate it.
926 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000927
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000928 // Don't bother for PHI nodes.
929 if (isa<PHINode>(User))
930 continue;
931
932 // Figure out which BB this cmp is used in.
933 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000934
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000935 // If this user is in the same block as the cmp, don't change the cmp.
936 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000937
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000938 // If we have already inserted a cmp into this block, use it.
939 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
940
941 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000942 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000943 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000944 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000945 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
946 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +0000947 // Propagate the debug info.
948 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000949 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000950
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000951 // Replace a use of the cmp with a use of the new cmp.
952 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000953 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000954 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000955 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000956
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000957 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000958 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000959 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000960 MadeChange = true;
961 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000962
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000963 return MadeChange;
964}
965
Peter Zotovf87e5502016-04-03 17:11:53 +0000966static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +0000967 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000968 return true;
969
970 if (CombineUAddWithOverflow(CI))
971 return true;
972
973 return false;
974}
975
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000976/// Check if the candidates could be combined with a shift instruction, which
977/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000978/// 1. Truncate instruction
979/// 2. And instruction and the imm is a mask of the low bits:
980/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000981static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000982 if (!isa<TruncInst>(User)) {
983 if (User->getOpcode() != Instruction::And ||
984 !isa<ConstantInt>(User->getOperand(1)))
985 return false;
986
Quentin Colombetd4f44692014-04-22 01:20:34 +0000987 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000988
Quentin Colombetd4f44692014-04-22 01:20:34 +0000989 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000990 return false;
991 }
992 return true;
993}
994
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000995/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000996static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000997SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
998 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000999 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001000 BasicBlock *UserBB = User->getParent();
1001 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1002 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1003 bool MadeChange = false;
1004
1005 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1006 TruncE = TruncI->user_end();
1007 TruncUI != TruncE;) {
1008
1009 Use &TruncTheUse = TruncUI.getUse();
1010 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1011 // Preincrement use iterator so we don't invalidate it.
1012
1013 ++TruncUI;
1014
1015 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1016 if (!ISDOpcode)
1017 continue;
1018
Tim Northovere2239ff2014-07-29 10:20:22 +00001019 // If the use is actually a legal node, there will not be an
1020 // implicit truncate.
1021 // FIXME: always querying the result type is just an
1022 // approximation; some nodes' legality is determined by the
1023 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001024 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001025 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001026 continue;
1027
1028 // Don't bother for PHI nodes.
1029 if (isa<PHINode>(TruncUser))
1030 continue;
1031
1032 BasicBlock *TruncUserBB = TruncUser->getParent();
1033
1034 if (UserBB == TruncUserBB)
1035 continue;
1036
1037 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1038 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1039
1040 if (!InsertedShift && !InsertedTrunc) {
1041 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001042 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001043 // Sink the shift
1044 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001045 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1046 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001047 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001048 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1049 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001050
1051 // Sink the trunc
1052 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1053 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001054 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001055
1056 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001057 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001058
1059 MadeChange = true;
1060
1061 TruncTheUse = InsertedTrunc;
1062 }
1063 }
1064 return MadeChange;
1065}
1066
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001067/// Sink the shift *right* instruction into user blocks if the uses could
1068/// potentially be combined with this shift instruction and generate BitExtract
1069/// instruction. It will only be applied if the architecture supports BitExtract
1070/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001071/// BB1:
1072/// %x.extract.shift = lshr i64 %arg1, 32
1073/// BB2:
1074/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1075/// ==>
1076///
1077/// BB2:
1078/// %x.extract.shift.1 = lshr i64 %arg1, 32
1079/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1080///
1081/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1082/// instruction.
1083/// Return true if any changes are made.
1084static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001085 const TargetLowering &TLI,
1086 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001087 BasicBlock *DefBB = ShiftI->getParent();
1088
1089 /// Only insert instructions in each block once.
1090 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1091
Mehdi Amini44ede332015-07-09 02:09:04 +00001092 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001093
1094 bool MadeChange = false;
1095 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1096 UI != E;) {
1097 Use &TheUse = UI.getUse();
1098 Instruction *User = cast<Instruction>(*UI);
1099 // Preincrement use iterator so we don't invalidate it.
1100 ++UI;
1101
1102 // Don't bother for PHI nodes.
1103 if (isa<PHINode>(User))
1104 continue;
1105
1106 if (!isExtractBitsCandidateUse(User))
1107 continue;
1108
1109 BasicBlock *UserBB = User->getParent();
1110
1111 if (UserBB == DefBB) {
1112 // If the shift and truncate instruction are in the same BB. The use of
1113 // the truncate(TruncUse) may still introduce another truncate if not
1114 // legal. In this case, we would like to sink both shift and truncate
1115 // instruction to the BB of TruncUse.
1116 // for example:
1117 // BB1:
1118 // i64 shift.result = lshr i64 opnd, imm
1119 // trunc.result = trunc shift.result to i16
1120 //
1121 // BB2:
1122 // ----> We will have an implicit truncate here if the architecture does
1123 // not have i16 compare.
1124 // cmp i16 trunc.result, opnd2
1125 //
1126 if (isa<TruncInst>(User) && shiftIsLegal
1127 // If the type of the truncate is legal, no trucate will be
1128 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001129 &&
1130 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001131 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001132 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001133
1134 continue;
1135 }
1136 // If we have already inserted a shift into this block, use it.
1137 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1138
1139 if (!InsertedShift) {
1140 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001141 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001142
1143 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001144 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1145 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001146 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001147 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1148 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001149
1150 MadeChange = true;
1151 }
1152
1153 // Replace a use of the shift with a use of the new shift.
1154 TheUse = InsertedShift;
1155 }
1156
1157 // If we removed all uses, nuke the shift.
1158 if (ShiftI->use_empty())
1159 ShiftI->eraseFromParent();
1160
1161 return MadeChange;
1162}
1163
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001164// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001165// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1166// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001167// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001168// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001169//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001170// %1 = bitcast i8* %addr to i32*
1171// %2 = extractelement <16 x i1> %mask, i32 0
1172// %3 = icmp eq i1 %2, true
1173// br i1 %3, label %cond.load, label %else
1174//
1175//cond.load: ; preds = %0
1176// %4 = getelementptr i32* %1, i32 0
1177// %5 = load i32* %4
1178// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1179// br label %else
1180//
1181//else: ; preds = %0, %cond.load
1182// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1183// %7 = extractelement <16 x i1> %mask, i32 1
1184// %8 = icmp eq i1 %7, true
1185// br i1 %8, label %cond.load1, label %else2
1186//
1187//cond.load1: ; preds = %else
1188// %9 = getelementptr i32* %1, i32 1
1189// %10 = load i32* %9
1190// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1191// br label %else2
1192//
1193//else2: ; preds = %else, %cond.load1
1194// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1195// %12 = extractelement <16 x i1> %mask, i32 2
1196// %13 = icmp eq i1 %12, true
1197// br i1 %13, label %cond.load4, label %else5
1198//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001199static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001200 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001201 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001202 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001203 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001204
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001205 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1206 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001207 assert(VecType && "Unexpected return type of masked load intrinsic");
1208
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001209 Type *EltTy = CI->getType()->getVectorElementType();
1210
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001211 IRBuilder<> Builder(CI->getContext());
1212 Instruction *InsertPt = CI;
1213 BasicBlock *IfBlock = CI->getParent();
1214 BasicBlock *CondBlock = nullptr;
1215 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001216
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001217 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001218 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1219
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001220 // Short-cut if the mask is all-true.
1221 bool IsAllOnesMask = isa<Constant>(Mask) &&
1222 cast<Constant>(Mask)->isAllOnesValue();
1223
1224 if (IsAllOnesMask) {
1225 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1226 CI->replaceAllUsesWith(NewI);
1227 CI->eraseFromParent();
1228 return;
1229 }
1230
1231 // Adjust alignment for the scalar instruction.
1232 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001233 // Bitcast %addr fron i8* to EltTy*
1234 Type *NewPtrType =
1235 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1236 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001237 unsigned VectorWidth = VecType->getNumElements();
1238
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001239 Value *UndefVal = UndefValue::get(VecType);
1240
1241 // The result vector
1242 Value *VResult = UndefVal;
1243
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001244 if (isa<ConstantVector>(Mask)) {
1245 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1246 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1247 continue;
1248 Value *Gep =
1249 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1250 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1251 VResult = Builder.CreateInsertElement(VResult, Load,
1252 Builder.getInt32(Idx));
1253 }
1254 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1255 CI->replaceAllUsesWith(NewI);
1256 CI->eraseFromParent();
1257 return;
1258 }
1259
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001260 PHINode *Phi = nullptr;
1261 Value *PrevPhi = UndefVal;
1262
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001263 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1264
1265 // Fill the "else" block, created in the previous iteration
1266 //
1267 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1268 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1269 // %to_load = icmp eq i1 %mask_1, true
1270 // br i1 %to_load, label %cond.load, label %else
1271 //
1272 if (Idx > 0) {
1273 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1274 Phi->addIncoming(VResult, CondBlock);
1275 Phi->addIncoming(PrevPhi, PrevIfBlock);
1276 PrevPhi = Phi;
1277 VResult = Phi;
1278 }
1279
1280 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1281 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1282 ConstantInt::get(Predicate->getType(), 1));
1283
1284 // Create "cond" block
1285 //
1286 // %EltAddr = getelementptr i32* %1, i32 0
1287 // %Elt = load i32* %EltAddr
1288 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1289 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001290 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001291 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001292
1293 Value *Gep =
1294 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001295 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001296 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1297
1298 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001299 BasicBlock *NewIfBlock =
1300 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001301 Builder.SetInsertPoint(InsertPt);
1302 Instruction *OldBr = IfBlock->getTerminator();
1303 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1304 OldBr->eraseFromParent();
1305 PrevIfBlock = IfBlock;
1306 IfBlock = NewIfBlock;
1307 }
1308
1309 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1310 Phi->addIncoming(VResult, CondBlock);
1311 Phi->addIncoming(PrevPhi, PrevIfBlock);
1312 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1313 CI->replaceAllUsesWith(NewI);
1314 CI->eraseFromParent();
1315}
1316
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001317// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001318// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1319// <16 x i1> %mask)
1320// to a chain of basic blocks, that stores element one-by-one if
1321// the appropriate mask bit is set
1322//
1323// %1 = bitcast i8* %addr to i32*
1324// %2 = extractelement <16 x i1> %mask, i32 0
1325// %3 = icmp eq i1 %2, true
1326// br i1 %3, label %cond.store, label %else
1327//
1328// cond.store: ; preds = %0
1329// %4 = extractelement <16 x i32> %val, i32 0
1330// %5 = getelementptr i32* %1, i32 0
1331// store i32 %4, i32* %5
1332// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001333//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001334// else: ; preds = %0, %cond.store
1335// %6 = extractelement <16 x i1> %mask, i32 1
1336// %7 = icmp eq i1 %6, true
1337// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001338//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001339// cond.store1: ; preds = %else
1340// %8 = extractelement <16 x i32> %val, i32 1
1341// %9 = getelementptr i32* %1, i32 1
1342// store i32 %8, i32* %9
1343// br label %else2
1344// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001345static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001346 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001347 Value *Ptr = CI->getArgOperand(1);
1348 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001349 Value *Mask = CI->getArgOperand(3);
1350
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001351 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001352 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001353 assert(VecType && "Unexpected data type in masked store intrinsic");
1354
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001355 Type *EltTy = VecType->getElementType();
1356
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001357 IRBuilder<> Builder(CI->getContext());
1358 Instruction *InsertPt = CI;
1359 BasicBlock *IfBlock = CI->getParent();
1360 Builder.SetInsertPoint(InsertPt);
1361 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1362
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001363 // Short-cut if the mask is all-true.
1364 bool IsAllOnesMask = isa<Constant>(Mask) &&
1365 cast<Constant>(Mask)->isAllOnesValue();
1366
1367 if (IsAllOnesMask) {
1368 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1369 CI->eraseFromParent();
1370 return;
1371 }
1372
1373 // Adjust alignment for the scalar instruction.
1374 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001375 // Bitcast %addr fron i8* to EltTy*
1376 Type *NewPtrType =
1377 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1378 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001379 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001380
1381 if (isa<ConstantVector>(Mask)) {
1382 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1383 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1384 continue;
1385 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1386 Value *Gep =
1387 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1388 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1389 }
1390 CI->eraseFromParent();
1391 return;
1392 }
1393
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001394 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1395
1396 // Fill the "else" block, created in the previous iteration
1397 //
1398 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1399 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001400 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001401 //
1402 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1403 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1404 ConstantInt::get(Predicate->getType(), 1));
1405
1406 // Create "cond" block
1407 //
1408 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1409 // %EltAddr = getelementptr i32* %1, i32 0
1410 // %store i32 %OneElt, i32* %EltAddr
1411 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001412 BasicBlock *CondBlock =
1413 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001414 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001415
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001416 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001417 Value *Gep =
1418 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001419 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001420
1421 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001422 BasicBlock *NewIfBlock =
1423 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001424 Builder.SetInsertPoint(InsertPt);
1425 Instruction *OldBr = IfBlock->getTerminator();
1426 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1427 OldBr->eraseFromParent();
1428 IfBlock = NewIfBlock;
1429 }
1430 CI->eraseFromParent();
1431}
1432
Elena Demikhovsky09285852015-10-25 15:37:55 +00001433// Translate a masked gather intrinsic like
1434// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1435// <16 x i1> %Mask, <16 x i32> %Src)
1436// to a chain of basic blocks, with loading element one-by-one if
1437// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001438//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001439// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1440// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1441// % ToLoad0 = icmp eq i1 % Mask0, true
1442// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001443//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001444// cond.load:
1445// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1446// % Load0 = load i32, i32* % Ptr0, align 4
1447// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1448// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001449//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001450// else:
1451// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1452// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1453// % ToLoad1 = icmp eq i1 % Mask1, true
1454// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001455//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001456// cond.load1:
1457// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1458// % Load1 = load i32, i32* % Ptr1, align 4
1459// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1460// br label %else2
1461// . . .
1462// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1463// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001464static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001465 Value *Ptrs = CI->getArgOperand(0);
1466 Value *Alignment = CI->getArgOperand(1);
1467 Value *Mask = CI->getArgOperand(2);
1468 Value *Src0 = CI->getArgOperand(3);
1469
1470 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1471
1472 assert(VecType && "Unexpected return type of masked load intrinsic");
1473
1474 IRBuilder<> Builder(CI->getContext());
1475 Instruction *InsertPt = CI;
1476 BasicBlock *IfBlock = CI->getParent();
1477 BasicBlock *CondBlock = nullptr;
1478 BasicBlock *PrevIfBlock = CI->getParent();
1479 Builder.SetInsertPoint(InsertPt);
1480 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1481
1482 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1483
1484 Value *UndefVal = UndefValue::get(VecType);
1485
1486 // The result vector
1487 Value *VResult = UndefVal;
1488 unsigned VectorWidth = VecType->getNumElements();
1489
1490 // Shorten the way if the mask is a vector of constants.
1491 bool IsConstMask = isa<ConstantVector>(Mask);
1492
1493 if (IsConstMask) {
1494 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1495 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1496 continue;
1497 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1498 "Ptr" + Twine(Idx));
1499 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1500 "Load" + Twine(Idx));
1501 VResult = Builder.CreateInsertElement(VResult, Load,
1502 Builder.getInt32(Idx),
1503 "Res" + Twine(Idx));
1504 }
1505 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1506 CI->replaceAllUsesWith(NewI);
1507 CI->eraseFromParent();
1508 return;
1509 }
1510
1511 PHINode *Phi = nullptr;
1512 Value *PrevPhi = UndefVal;
1513
1514 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1515
1516 // Fill the "else" block, created in the previous iteration
1517 //
1518 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1519 // %ToLoad1 = icmp eq i1 %Mask1, true
1520 // br i1 %ToLoad1, label %cond.load, label %else
1521 //
1522 if (Idx > 0) {
1523 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1524 Phi->addIncoming(VResult, CondBlock);
1525 Phi->addIncoming(PrevPhi, PrevIfBlock);
1526 PrevPhi = Phi;
1527 VResult = Phi;
1528 }
1529
1530 Value *Predicate = Builder.CreateExtractElement(Mask,
1531 Builder.getInt32(Idx),
1532 "Mask" + Twine(Idx));
1533 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1534 ConstantInt::get(Predicate->getType(), 1),
1535 "ToLoad" + Twine(Idx));
1536
1537 // Create "cond" block
1538 //
1539 // %EltAddr = getelementptr i32* %1, i32 0
1540 // %Elt = load i32* %EltAddr
1541 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1542 //
1543 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1544 Builder.SetInsertPoint(InsertPt);
1545
1546 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1547 "Ptr" + Twine(Idx));
1548 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1549 "Load" + Twine(Idx));
1550 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1551 "Res" + Twine(Idx));
1552
1553 // Create "else" block, fill it in the next iteration
1554 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1555 Builder.SetInsertPoint(InsertPt);
1556 Instruction *OldBr = IfBlock->getTerminator();
1557 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1558 OldBr->eraseFromParent();
1559 PrevIfBlock = IfBlock;
1560 IfBlock = NewIfBlock;
1561 }
1562
1563 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1564 Phi->addIncoming(VResult, CondBlock);
1565 Phi->addIncoming(PrevPhi, PrevIfBlock);
1566 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1567 CI->replaceAllUsesWith(NewI);
1568 CI->eraseFromParent();
1569}
1570
1571// Translate a masked scatter intrinsic, like
1572// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1573// <16 x i1> %Mask)
1574// to a chain of basic blocks, that stores element one-by-one if
1575// the appropriate mask bit is set.
1576//
1577// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1578// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1579// % ToStore0 = icmp eq i1 % Mask0, true
1580// br i1 %ToStore0, label %cond.store, label %else
1581//
1582// cond.store:
1583// % Elt0 = extractelement <16 x i32> %Src, i32 0
1584// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1585// store i32 %Elt0, i32* % Ptr0, align 4
1586// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001587//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001588// else:
1589// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1590// % ToStore1 = icmp eq i1 % Mask1, true
1591// br i1 % ToStore1, label %cond.store1, label %else2
1592//
1593// cond.store1:
1594// % Elt1 = extractelement <16 x i32> %Src, i32 1
1595// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1596// store i32 % Elt1, i32* % Ptr1, align 4
1597// br label %else2
1598// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001599static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001600 Value *Src = CI->getArgOperand(0);
1601 Value *Ptrs = CI->getArgOperand(1);
1602 Value *Alignment = CI->getArgOperand(2);
1603 Value *Mask = CI->getArgOperand(3);
1604
1605 assert(isa<VectorType>(Src->getType()) &&
1606 "Unexpected data type in masked scatter intrinsic");
1607 assert(isa<VectorType>(Ptrs->getType()) &&
1608 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1609 "Vector of pointers is expected in masked scatter intrinsic");
1610
1611 IRBuilder<> Builder(CI->getContext());
1612 Instruction *InsertPt = CI;
1613 BasicBlock *IfBlock = CI->getParent();
1614 Builder.SetInsertPoint(InsertPt);
1615 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1616
1617 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1618 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1619
1620 // Shorten the way if the mask is a vector of constants.
1621 bool IsConstMask = isa<ConstantVector>(Mask);
1622
1623 if (IsConstMask) {
1624 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1625 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1626 continue;
1627 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1628 "Elt" + Twine(Idx));
1629 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1630 "Ptr" + Twine(Idx));
1631 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1632 }
1633 CI->eraseFromParent();
1634 return;
1635 }
1636 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1637 // Fill the "else" block, created in the previous iteration
1638 //
1639 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1640 // % ToStore = icmp eq i1 % Mask1, true
1641 // br i1 % ToStore, label %cond.store, label %else
1642 //
1643 Value *Predicate = Builder.CreateExtractElement(Mask,
1644 Builder.getInt32(Idx),
1645 "Mask" + Twine(Idx));
1646 Value *Cmp =
1647 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1648 ConstantInt::get(Predicate->getType(), 1),
1649 "ToStore" + Twine(Idx));
1650
1651 // Create "cond" block
1652 //
1653 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1654 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1655 // %store i32 % Elt1, i32* % Ptr1
1656 //
1657 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1658 Builder.SetInsertPoint(InsertPt);
1659
1660 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1661 "Elt" + Twine(Idx));
1662 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1663 "Ptr" + Twine(Idx));
1664 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1665
1666 // Create "else" block, fill it in the next iteration
1667 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1668 Builder.SetInsertPoint(InsertPt);
1669 Instruction *OldBr = IfBlock->getTerminator();
1670 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1671 OldBr->eraseFromParent();
1672 IfBlock = NewIfBlock;
1673 }
1674 CI->eraseFromParent();
1675}
1676
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001677/// If counting leading or trailing zeros is an expensive operation and a zero
1678/// input is defined, add a check for zero to avoid calling the intrinsic.
1679///
1680/// We want to transform:
1681/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1682///
1683/// into:
1684/// entry:
1685/// %cmpz = icmp eq i64 %A, 0
1686/// br i1 %cmpz, label %cond.end, label %cond.false
1687/// cond.false:
1688/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1689/// br label %cond.end
1690/// cond.end:
1691/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1692///
1693/// If the transform is performed, return true and set ModifiedDT to true.
1694static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1695 const TargetLowering *TLI,
1696 const DataLayout *DL,
1697 bool &ModifiedDT) {
1698 if (!TLI || !DL)
1699 return false;
1700
1701 // If a zero input is undefined, it doesn't make sense to despeculate that.
1702 if (match(CountZeros->getOperand(1), m_One()))
1703 return false;
1704
1705 // If it's cheap to speculate, there's nothing to do.
1706 auto IntrinsicID = CountZeros->getIntrinsicID();
1707 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1708 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1709 return false;
1710
1711 // Only handle legal scalar cases. Anything else requires too much work.
1712 Type *Ty = CountZeros->getType();
1713 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001714 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001715 return false;
1716
1717 // The intrinsic will be sunk behind a compare against zero and branch.
1718 BasicBlock *StartBlock = CountZeros->getParent();
1719 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1720
1721 // Create another block after the count zero intrinsic. A PHI will be added
1722 // in this block to select the result of the intrinsic or the bit-width
1723 // constant if the input to the intrinsic is zero.
1724 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1725 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1726
1727 // Set up a builder to create a compare, conditional branch, and PHI.
1728 IRBuilder<> Builder(CountZeros->getContext());
1729 Builder.SetInsertPoint(StartBlock->getTerminator());
1730 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1731
1732 // Replace the unconditional branch that was created by the first split with
1733 // a compare against zero and a conditional branch.
1734 Value *Zero = Constant::getNullValue(Ty);
1735 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1736 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1737 StartBlock->getTerminator()->eraseFromParent();
1738
1739 // Create a PHI in the end block to select either the output of the intrinsic
1740 // or the bit width of the operand.
1741 Builder.SetInsertPoint(&EndBlock->front());
1742 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1743 CountZeros->replaceAllUsesWith(PN);
1744 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1745 PN->addIncoming(BitWidth, StartBlock);
1746 PN->addIncoming(CountZeros, CallBlock);
1747
1748 // We are explicitly handling the zero case, so we can set the intrinsic's
1749 // undefined zero argument to 'true'. This will also prevent reprocessing the
1750 // intrinsic; we only despeculate when a zero input is defined.
1751 CountZeros->setArgOperand(1, Builder.getTrue());
1752 ModifiedDT = true;
1753 return true;
1754}
1755
Sanjay Patelfc580a62015-09-21 23:03:16 +00001756bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001757 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001758
Chris Lattner7a277142011-01-15 07:14:54 +00001759 // Lower inline assembly if we can.
1760 // If we found an inline asm expession, and if the target knows how to
1761 // lower it to normal LLVM code, do so now.
1762 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1763 if (TLI->ExpandInlineAsm(CI)) {
1764 // Avoid invalidating the iterator.
1765 CurInstIterator = BB->begin();
1766 // Avoid processing instructions out of order, which could cause
1767 // reuse before a value is defined.
1768 SunkAddrs.clear();
1769 return true;
1770 }
1771 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001772 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001773 return true;
1774 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001775
John Brawn0dbcd652015-03-18 12:01:59 +00001776 // Align the pointer arguments to this call if the target thinks it's a good
1777 // idea
1778 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001779 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001780 for (auto &Arg : CI->arg_operands()) {
1781 // We want to align both objects whose address is used directly and
1782 // objects whose address is used in casts and GEPs, though it only makes
1783 // sense for GEPs if the offset is a multiple of the desired alignment and
1784 // if size - offset meets the size threshold.
1785 if (!Arg->getType()->isPointerTy())
1786 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001787 APInt Offset(DL->getPointerSizeInBits(
1788 cast<PointerType>(Arg->getType())->getAddressSpace()),
1789 0);
1790 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001791 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001792 if ((Offset2 & (PrefAlign-1)) != 0)
1793 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001794 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001795 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1796 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001797 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001798 // Global variables can only be aligned if they are defined in this
1799 // object (i.e. they are uniquely initialized in this object), and
1800 // over-aligning global variables that have an explicit section is
1801 // forbidden.
1802 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001803 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001804 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001805 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001806 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001807 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001808 }
1809 // If this is a memcpy (or similar) then we may be able to improve the
1810 // alignment
1811 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001812 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001813 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001814 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001815 if (Align > MI->getAlignment())
1816 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001817 }
1818 }
1819
Philip Reamesac115ed2016-03-09 23:13:12 +00001820 // If we have a cold call site, try to sink addressing computation into the
1821 // cold block. This interacts with our handling for loads and stores to
1822 // ensure that we can fold all uses of a potential addressing computation
1823 // into their uses. TODO: generalize this to work over profiling data
1824 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1825 for (auto &Arg : CI->arg_operands()) {
1826 if (!Arg->getType()->isPointerTy())
1827 continue;
1828 unsigned AS = Arg->getType()->getPointerAddressSpace();
1829 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1830 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001831
Eric Christopher4b7948e2010-03-11 02:41:03 +00001832 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001833 if (II) {
1834 switch (II->getIntrinsicID()) {
1835 default: break;
1836 case Intrinsic::objectsize: {
1837 // Lower all uses of llvm.objectsize.*
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001838 uint64_t Size;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001839 Type *ReturnTy = CI->getType();
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001840 Constant *RetVal = nullptr;
1841 ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1));
1842 ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min;
1843 if (getObjectSize(II->getArgOperand(0),
1844 Size, *DL, TLInfo, false, Mode)) {
1845 RetVal = ConstantInt::get(ReturnTy, Size);
1846 } else {
1847 RetVal = ConstantInt::get(ReturnTy,
1848 Mode == ObjSizeMode::Min ? 0 : -1ULL);
1849 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001850 // Substituting this can cause recursive simplifications, which can
1851 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1852 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001853 Value *CurValue = &*CurInstIterator;
1854 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001855
Sanjay Patel545a4562016-01-20 18:59:16 +00001856 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001857
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001858 // If the iterator instruction was recursively deleted, start over at the
1859 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001860 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001861 CurInstIterator = BB->begin();
1862 SunkAddrs.clear();
1863 }
1864 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001865 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001866 case Intrinsic::masked_load: {
1867 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001868 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001869 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001870 ModifiedDT = true;
1871 return true;
1872 }
1873 return false;
1874 }
1875 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001876 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001877 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001878 ModifiedDT = true;
1879 return true;
1880 }
1881 return false;
1882 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001883 case Intrinsic::masked_gather: {
1884 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001885 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001886 ModifiedDT = true;
1887 return true;
1888 }
1889 return false;
1890 }
1891 case Intrinsic::masked_scatter: {
1892 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001893 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001894 ModifiedDT = true;
1895 return true;
1896 }
1897 return false;
1898 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001899 case Intrinsic::aarch64_stlxr:
1900 case Intrinsic::aarch64_stxr: {
1901 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1902 if (!ExtVal || !ExtVal->hasOneUse() ||
1903 ExtVal->getParent() == CI->getParent())
1904 return false;
1905 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1906 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001907 // Mark this instruction as "inserted by CGP", so that other
1908 // optimizations don't touch it.
1909 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001910 return true;
1911 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001912 case Intrinsic::invariant_group_barrier:
1913 II->replaceAllUsesWith(II->getArgOperand(0));
1914 II->eraseFromParent();
1915 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001916
1917 case Intrinsic::cttz:
1918 case Intrinsic::ctlz:
1919 // If counting zeros is expensive, try to avoid it.
1920 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001921 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001922
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001923 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001924 // Unknown address space.
1925 // TODO: Target hook to pick which address space the intrinsic cares
1926 // about?
1927 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001928 SmallVector<Value*, 2> PtrOps;
1929 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001930 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001931 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001932 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001933 return true;
1934 }
Pete Cooper615fd892012-03-13 20:59:56 +00001935 }
1936
Eric Christopher4b7948e2010-03-11 02:41:03 +00001937 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001938 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001939
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001940 // Lower all default uses of _chk calls. This is very similar
1941 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001942 // to fortified library functions (e.g. __memcpy_chk) that have the default
1943 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001944 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001945 if (Value *V = Simplifier.optimizeCall(CI)) {
1946 CI->replaceAllUsesWith(V);
1947 CI->eraseFromParent();
1948 return true;
1949 }
1950 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001951}
Chris Lattner1b93be52011-01-15 07:25:29 +00001952
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001953/// Look for opportunities to duplicate return instructions to the predecessor
1954/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001955/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001956/// bb0:
1957/// %tmp0 = tail call i32 @f0()
1958/// br label %return
1959/// bb1:
1960/// %tmp1 = tail call i32 @f1()
1961/// br label %return
1962/// bb2:
1963/// %tmp2 = tail call i32 @f2()
1964/// br label %return
1965/// return:
1966/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1967/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001968/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001969///
1970/// =>
1971///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001972/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001973/// bb0:
1974/// %tmp0 = tail call i32 @f0()
1975/// ret i32 %tmp0
1976/// bb1:
1977/// %tmp1 = tail call i32 @f1()
1978/// ret i32 %tmp1
1979/// bb2:
1980/// %tmp2 = tail call i32 @f2()
1981/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001982/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001983bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001984 if (!TLI)
1985 return false;
1986
Michael Kuperstein71321562016-09-07 20:29:49 +00001987 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1988 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001989 return false;
1990
Craig Topperc0196b12014-04-14 00:51:57 +00001991 PHINode *PN = nullptr;
1992 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001993 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001994 if (V) {
1995 BCI = dyn_cast<BitCastInst>(V);
1996 if (BCI)
1997 V = BCI->getOperand(0);
1998
1999 PN = dyn_cast<PHINode>(V);
2000 if (!PN)
2001 return false;
2002 }
Evan Cheng0663f232011-03-21 01:19:09 +00002003
Cameron Zwarich4649f172011-03-24 04:52:10 +00002004 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002005 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002006
Cameron Zwarich4649f172011-03-24 04:52:10 +00002007 // Make sure there are no instructions between the PHI and return, or that the
2008 // return is the first instruction in the block.
2009 if (PN) {
2010 BasicBlock::iterator BI = BB->begin();
2011 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002012 if (&*BI == BCI)
2013 // Also skip over the bitcast.
2014 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002015 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002016 return false;
2017 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002018 BasicBlock::iterator BI = BB->begin();
2019 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002020 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002021 return false;
2022 }
Evan Cheng0663f232011-03-21 01:19:09 +00002023
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002024 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2025 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002026 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002027 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002028 if (PN) {
2029 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2030 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2031 // Make sure the phi value is indeed produced by the tail call.
2032 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002033 TLI->mayBeEmittedAsTailCall(CI) &&
2034 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002035 TailCalls.push_back(CI);
2036 }
2037 } else {
2038 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002039 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002040 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002041 continue;
2042
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002043 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002044 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2045 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002046 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2047 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002048 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002049
Cameron Zwarich4649f172011-03-24 04:52:10 +00002050 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002051 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2052 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002053 TailCalls.push_back(CI);
2054 }
Evan Cheng0663f232011-03-21 01:19:09 +00002055 }
2056
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002057 bool Changed = false;
2058 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2059 CallInst *CI = TailCalls[i];
2060 CallSite CS(CI);
2061
2062 // Conservatively require the attributes of the call to match those of the
2063 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002064 AttributeSet CalleeAttrs = CS.getAttributes();
2065 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002066 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002067 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002068 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002069 continue;
2070
2071 // Make sure the call instruction is followed by an unconditional branch to
2072 // the return block.
2073 BasicBlock *CallBB = CI->getParent();
2074 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2075 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2076 continue;
2077
2078 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002079 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002080 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002081 ++NumRetsDup;
2082 }
2083
2084 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002085 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002086 BB->eraseFromParent();
2087
2088 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002089}
2090
Chris Lattner728f9022008-11-25 07:09:13 +00002091//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002092// Memory Optimization
2093//===----------------------------------------------------------------------===//
2094
Chandler Carruthc8925912013-01-05 02:09:22 +00002095namespace {
2096
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002097/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002098/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002099struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002100 Value *BaseReg;
2101 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002102 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002103 void print(raw_ostream &OS) const;
2104 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002105
Chandler Carruthc8925912013-01-05 02:09:22 +00002106 bool operator==(const ExtAddrMode& O) const {
2107 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2108 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2109 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2110 }
2111};
2112
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002113#ifndef NDEBUG
2114static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2115 AM.print(OS);
2116 return OS;
2117}
2118#endif
2119
Chandler Carruthc8925912013-01-05 02:09:22 +00002120void ExtAddrMode::print(raw_ostream &OS) const {
2121 bool NeedPlus = false;
2122 OS << "[";
2123 if (BaseGV) {
2124 OS << (NeedPlus ? " + " : "")
2125 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002126 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002127 NeedPlus = true;
2128 }
2129
Richard Trieuc0f91212014-05-30 03:15:17 +00002130 if (BaseOffs) {
2131 OS << (NeedPlus ? " + " : "")
2132 << BaseOffs;
2133 NeedPlus = true;
2134 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002135
2136 if (BaseReg) {
2137 OS << (NeedPlus ? " + " : "")
2138 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002139 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002140 NeedPlus = true;
2141 }
2142 if (Scale) {
2143 OS << (NeedPlus ? " + " : "")
2144 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002145 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002146 }
2147
2148 OS << ']';
2149}
2150
2151#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002152LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002153 print(dbgs());
2154 dbgs() << '\n';
2155}
2156#endif
2157
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002158/// \brief This class provides transaction based operation on the IR.
2159/// Every change made through this class is recorded in the internal state and
2160/// can be undone (rollback) until commit is called.
2161class TypePromotionTransaction {
2162
2163 /// \brief This represents the common interface of the individual transaction.
2164 /// Each class implements the logic for doing one specific modification on
2165 /// the IR via the TypePromotionTransaction.
2166 class TypePromotionAction {
2167 protected:
2168 /// The Instruction modified.
2169 Instruction *Inst;
2170
2171 public:
2172 /// \brief Constructor of the action.
2173 /// The constructor performs the related action on the IR.
2174 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2175
2176 virtual ~TypePromotionAction() {}
2177
2178 /// \brief Undo the modification done by this action.
2179 /// When this method is called, the IR must be in the same state as it was
2180 /// before this action was applied.
2181 /// \pre Undoing the action works if and only if the IR is in the exact same
2182 /// state as it was directly after this action was applied.
2183 virtual void undo() = 0;
2184
2185 /// \brief Advocate every change made by this action.
2186 /// When the results on the IR of the action are to be kept, it is important
2187 /// to call this function, otherwise hidden information may be kept forever.
2188 virtual void commit() {
2189 // Nothing to be done, this action is not doing anything.
2190 }
2191 };
2192
2193 /// \brief Utility to remember the position of an instruction.
2194 class InsertionHandler {
2195 /// Position of an instruction.
2196 /// Either an instruction:
2197 /// - Is the first in a basic block: BB is used.
2198 /// - Has a previous instructon: PrevInst is used.
2199 union {
2200 Instruction *PrevInst;
2201 BasicBlock *BB;
2202 } Point;
2203 /// Remember whether or not the instruction had a previous instruction.
2204 bool HasPrevInstruction;
2205
2206 public:
2207 /// \brief Record the position of \p Inst.
2208 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002209 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002210 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2211 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002212 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002213 else
2214 Point.BB = Inst->getParent();
2215 }
2216
2217 /// \brief Insert \p Inst at the recorded position.
2218 void insert(Instruction *Inst) {
2219 if (HasPrevInstruction) {
2220 if (Inst->getParent())
2221 Inst->removeFromParent();
2222 Inst->insertAfter(Point.PrevInst);
2223 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002224 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002225 if (Inst->getParent())
2226 Inst->moveBefore(Position);
2227 else
2228 Inst->insertBefore(Position);
2229 }
2230 }
2231 };
2232
2233 /// \brief Move an instruction before another.
2234 class InstructionMoveBefore : public TypePromotionAction {
2235 /// Original position of the instruction.
2236 InsertionHandler Position;
2237
2238 public:
2239 /// \brief Move \p Inst before \p Before.
2240 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2241 : TypePromotionAction(Inst), Position(Inst) {
2242 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2243 Inst->moveBefore(Before);
2244 }
2245
2246 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002247 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002248 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2249 Position.insert(Inst);
2250 }
2251 };
2252
2253 /// \brief Set the operand of an instruction with a new value.
2254 class OperandSetter : public TypePromotionAction {
2255 /// Original operand of the instruction.
2256 Value *Origin;
2257 /// Index of the modified instruction.
2258 unsigned Idx;
2259
2260 public:
2261 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2262 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2263 : TypePromotionAction(Inst), Idx(Idx) {
2264 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2265 << "for:" << *Inst << "\n"
2266 << "with:" << *NewVal << "\n");
2267 Origin = Inst->getOperand(Idx);
2268 Inst->setOperand(Idx, NewVal);
2269 }
2270
2271 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002272 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002273 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2274 << "for: " << *Inst << "\n"
2275 << "with: " << *Origin << "\n");
2276 Inst->setOperand(Idx, Origin);
2277 }
2278 };
2279
2280 /// \brief Hide the operands of an instruction.
2281 /// Do as if this instruction was not using any of its operands.
2282 class OperandsHider : public TypePromotionAction {
2283 /// The list of original operands.
2284 SmallVector<Value *, 4> OriginalValues;
2285
2286 public:
2287 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2288 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2289 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2290 unsigned NumOpnds = Inst->getNumOperands();
2291 OriginalValues.reserve(NumOpnds);
2292 for (unsigned It = 0; It < NumOpnds; ++It) {
2293 // Save the current operand.
2294 Value *Val = Inst->getOperand(It);
2295 OriginalValues.push_back(Val);
2296 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002297 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002298 // that we are not willing to pay.
2299 Inst->setOperand(It, UndefValue::get(Val->getType()));
2300 }
2301 }
2302
2303 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002304 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002305 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2306 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2307 Inst->setOperand(It, OriginalValues[It]);
2308 }
2309 };
2310
2311 /// \brief Build a truncate instruction.
2312 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002313 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002314 public:
2315 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2316 /// result.
2317 /// trunc Opnd to Ty.
2318 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2319 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002320 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2321 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322 }
2323
Quentin Colombetac55b152014-09-16 22:36:07 +00002324 /// \brief Get the built value.
2325 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326
2327 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002328 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002329 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2330 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2331 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002332 }
2333 };
2334
2335 /// \brief Build a sign extension instruction.
2336 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002337 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002338 public:
2339 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2340 /// result.
2341 /// sext Opnd to Ty.
2342 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002343 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002344 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002345 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2346 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002347 }
2348
Quentin Colombetac55b152014-09-16 22:36:07 +00002349 /// \brief Get the built value.
2350 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002351
2352 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002353 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002354 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2355 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2356 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002357 }
2358 };
2359
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002360 /// \brief Build a zero extension instruction.
2361 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002362 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002363 public:
2364 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2365 /// result.
2366 /// zext Opnd to Ty.
2367 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002368 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002369 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002370 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2371 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002372 }
2373
Quentin Colombetac55b152014-09-16 22:36:07 +00002374 /// \brief Get the built value.
2375 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002376
2377 /// \brief Remove the built instruction.
2378 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002379 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2380 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2381 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002382 }
2383 };
2384
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002385 /// \brief Mutate an instruction to another type.
2386 class TypeMutator : public TypePromotionAction {
2387 /// Record the original type.
2388 Type *OrigTy;
2389
2390 public:
2391 /// \brief Mutate the type of \p Inst into \p NewTy.
2392 TypeMutator(Instruction *Inst, Type *NewTy)
2393 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2394 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2395 << "\n");
2396 Inst->mutateType(NewTy);
2397 }
2398
2399 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002400 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2402 << "\n");
2403 Inst->mutateType(OrigTy);
2404 }
2405 };
2406
2407 /// \brief Replace the uses of an instruction by another instruction.
2408 class UsesReplacer : public TypePromotionAction {
2409 /// Helper structure to keep track of the replaced uses.
2410 struct InstructionAndIdx {
2411 /// The instruction using the instruction.
2412 Instruction *Inst;
2413 /// The index where this instruction is used for Inst.
2414 unsigned Idx;
2415 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2416 : Inst(Inst), Idx(Idx) {}
2417 };
2418
2419 /// Keep track of the original uses (pair Instruction, Index).
2420 SmallVector<InstructionAndIdx, 4> OriginalUses;
2421 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2422
2423 public:
2424 /// \brief Replace all the use of \p Inst by \p New.
2425 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2426 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2427 << "\n");
2428 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002429 for (Use &U : Inst->uses()) {
2430 Instruction *UserI = cast<Instruction>(U.getUser());
2431 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002432 }
2433 // Now, we can replace the uses.
2434 Inst->replaceAllUsesWith(New);
2435 }
2436
2437 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002438 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2440 for (use_iterator UseIt = OriginalUses.begin(),
2441 EndIt = OriginalUses.end();
2442 UseIt != EndIt; ++UseIt) {
2443 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2444 }
2445 }
2446 };
2447
2448 /// \brief Remove an instruction from the IR.
2449 class InstructionRemover : public TypePromotionAction {
2450 /// Original position of the instruction.
2451 InsertionHandler Inserter;
2452 /// Helper structure to hide all the link to the instruction. In other
2453 /// words, this helps to do as if the instruction was removed.
2454 OperandsHider Hider;
2455 /// Keep track of the uses replaced, if any.
2456 UsesReplacer *Replacer;
2457
2458 public:
2459 /// \brief Remove all reference of \p Inst and optinally replace all its
2460 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002461 /// \pre If !Inst->use_empty(), then New != nullptr
2462 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002463 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002464 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002465 if (New)
2466 Replacer = new UsesReplacer(Inst, New);
2467 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2468 Inst->removeFromParent();
2469 }
2470
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002471 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002472
2473 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002474 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002475
2476 /// \brief Resurrect the instruction and reassign it to the proper uses if
2477 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002478 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002479 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2480 Inserter.insert(Inst);
2481 if (Replacer)
2482 Replacer->undo();
2483 Hider.undo();
2484 }
2485 };
2486
2487public:
2488 /// Restoration point.
2489 /// The restoration point is a pointer to an action instead of an iterator
2490 /// because the iterator may be invalidated but not the pointer.
2491 typedef const TypePromotionAction *ConstRestorationPt;
2492 /// Advocate every changes made in that transaction.
2493 void commit();
2494 /// Undo all the changes made after the given point.
2495 void rollback(ConstRestorationPt Point);
2496 /// Get the current restoration point.
2497 ConstRestorationPt getRestorationPoint() const;
2498
2499 /// \name API for IR modification with state keeping to support rollback.
2500 /// @{
2501 /// Same as Instruction::setOperand.
2502 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2503 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002504 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002505 /// Same as Value::replaceAllUsesWith.
2506 void replaceAllUsesWith(Instruction *Inst, Value *New);
2507 /// Same as Value::mutateType.
2508 void mutateType(Instruction *Inst, Type *NewTy);
2509 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002510 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002512 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002513 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002514 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002515 /// Same as Instruction::moveBefore.
2516 void moveBefore(Instruction *Inst, Instruction *Before);
2517 /// @}
2518
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002519private:
2520 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002521 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2522 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002523};
2524
2525void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2526 Value *NewVal) {
2527 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002528 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002529}
2530
2531void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2532 Value *NewVal) {
2533 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002534 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002535}
2536
2537void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2538 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002539 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002540}
2541
2542void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002543 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002544}
2545
Quentin Colombetac55b152014-09-16 22:36:07 +00002546Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2547 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002548 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002549 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002550 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002551 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002552}
2553
Quentin Colombetac55b152014-09-16 22:36:07 +00002554Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2555 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002556 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002557 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002558 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002559 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002560}
2561
Quentin Colombetac55b152014-09-16 22:36:07 +00002562Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2563 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002564 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002565 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002566 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002567 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002568}
2569
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002570void TypePromotionTransaction::moveBefore(Instruction *Inst,
2571 Instruction *Before) {
2572 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002573 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002574}
2575
2576TypePromotionTransaction::ConstRestorationPt
2577TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002578 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002579}
2580
2581void TypePromotionTransaction::commit() {
2582 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002583 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002584 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002585 Actions.clear();
2586}
2587
2588void TypePromotionTransaction::rollback(
2589 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002590 while (!Actions.empty() && Point != Actions.back().get()) {
2591 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002592 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002593 }
2594}
2595
Chandler Carruthc8925912013-01-05 02:09:22 +00002596/// \brief A helper class for matching addressing modes.
2597///
2598/// This encapsulates the logic for matching the target-legal addressing modes.
2599class AddressingModeMatcher {
2600 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002601 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002602 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002603 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002604
2605 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2606 /// the memory instruction that we're computing this address for.
2607 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002608 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002609 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002610
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002611 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002612 /// part of the return value of this addressing mode matching stuff.
2613 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002614
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002615 /// The instructions inserted by other CodeGenPrepare optimizations.
2616 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002617 /// A map from the instructions to their type before promotion.
2618 InstrToOrigTy &PromotedInsts;
2619 /// The ongoing transaction where every action should be registered.
2620 TypePromotionTransaction &TPT;
2621
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002622 /// This is set to true when we should not do profitability checks.
2623 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002624 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002625
Eric Christopherd75c00c2015-02-26 22:38:34 +00002626 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002627 const TargetMachine &TM, Type *AT, unsigned AS,
2628 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002629 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002630 InstrToOrigTy &PromotedInsts,
2631 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002632 : AddrModeInsts(AMI), TM(TM),
2633 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2634 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002635 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2636 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2637 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002638 IgnoreProfitability = false;
2639 }
2640public:
Stephen Lin837bba12013-07-15 17:55:02 +00002641
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002642 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002643 /// give an access type of AccessTy. This returns a list of involved
2644 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002645 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002646 /// optimizations.
2647 /// \p PromotedInsts maps the instructions to their type before promotion.
2648 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002649 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002650 Instruction *MemoryInst,
2651 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002652 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002653 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002654 InstrToOrigTy &PromotedInsts,
2655 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002656 ExtAddrMode Result;
2657
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002658 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002659 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002660 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002661 (void)Success; assert(Success && "Couldn't select *anything*?");
2662 return Result;
2663 }
2664private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002665 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2666 bool matchAddr(Value *V, unsigned Depth);
2667 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002668 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002669 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002670 ExtAddrMode &AMBefore,
2671 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002672 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2673 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002674 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002675};
2676
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002677/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002678/// Return true and update AddrMode if this addr mode is legal for the target,
2679/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002680bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002681 unsigned Depth) {
2682 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2683 // mode. Just process that directly.
2684 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002685 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002686
Chandler Carruthc8925912013-01-05 02:09:22 +00002687 // If the scale is 0, it takes nothing to add this.
2688 if (Scale == 0)
2689 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002690
Chandler Carruthc8925912013-01-05 02:09:22 +00002691 // If we already have a scale of this value, we can add to it, otherwise, we
2692 // need an available scale field.
2693 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2694 return false;
2695
2696 ExtAddrMode TestAddrMode = AddrMode;
2697
2698 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2699 // [A+B + A*7] -> [B+A*8].
2700 TestAddrMode.Scale += Scale;
2701 TestAddrMode.ScaledReg = ScaleReg;
2702
2703 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002704 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002705 return false;
2706
2707 // It was legal, so commit it.
2708 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002709
Chandler Carruthc8925912013-01-05 02:09:22 +00002710 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2711 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2712 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002713 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002714 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2715 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2716 TestAddrMode.ScaledReg = AddLHS;
2717 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002718
Chandler Carruthc8925912013-01-05 02:09:22 +00002719 // If this addressing mode is legal, commit it and remember that we folded
2720 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002721 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002722 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2723 AddrMode = TestAddrMode;
2724 return true;
2725 }
2726 }
2727
2728 // Otherwise, not (x+c)*scale, just return what we have.
2729 return true;
2730}
2731
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002732/// This is a little filter, which returns true if an addressing computation
2733/// involving I might be folded into a load/store accessing it.
2734/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002735/// the set of instructions that MatchOperationAddr can.
2736static bool MightBeFoldableInst(Instruction *I) {
2737 switch (I->getOpcode()) {
2738 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002739 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002740 // Don't touch identity bitcasts.
2741 if (I->getType() == I->getOperand(0)->getType())
2742 return false;
2743 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2744 case Instruction::PtrToInt:
2745 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2746 return true;
2747 case Instruction::IntToPtr:
2748 // We know the input is intptr_t, so this is foldable.
2749 return true;
2750 case Instruction::Add:
2751 return true;
2752 case Instruction::Mul:
2753 case Instruction::Shl:
2754 // Can only handle X*C and X << C.
2755 return isa<ConstantInt>(I->getOperand(1));
2756 case Instruction::GetElementPtr:
2757 return true;
2758 default:
2759 return false;
2760 }
2761}
2762
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002763/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2764/// \note \p Val is assumed to be the product of some type promotion.
2765/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2766/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002767static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2768 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002769 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2770 if (!PromotedInst)
2771 return false;
2772 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2773 // If the ISDOpcode is undefined, it was undefined before the promotion.
2774 if (!ISDOpcode)
2775 return true;
2776 // Otherwise, check if the promoted instruction is legal or not.
2777 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002778 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002779}
2780
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002781/// \brief Hepler class to perform type promotion.
2782class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002783 /// \brief Utility function to check whether or not a sign or zero extension
2784 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2785 /// either using the operands of \p Inst or promoting \p Inst.
2786 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002787 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002788 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002789 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002790 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002791 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002792 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002793 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002794 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2795 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002796
2797 /// \brief Utility function to determine if \p OpIdx should be promoted when
2798 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002799 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002800 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002801 }
2802
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002803 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002804 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002805 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002806 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002807 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002808 /// Newly added extensions are inserted in \p Exts.
2809 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002810 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002811 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002812 static Value *promoteOperandForTruncAndAnyExt(
2813 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002814 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002815 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002816 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002817
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002818 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002819 /// operand is promotable and is not a supported trunc or sext.
2820 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002821 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002822 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002823 /// Newly added extensions are inserted in \p Exts.
2824 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002825 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002826 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002827 static Value *promoteOperandForOther(Instruction *Ext,
2828 TypePromotionTransaction &TPT,
2829 InstrToOrigTy &PromotedInsts,
2830 unsigned &CreatedInstsCost,
2831 SmallVectorImpl<Instruction *> *Exts,
2832 SmallVectorImpl<Instruction *> *Truncs,
2833 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002834
2835 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002836 static Value *signExtendOperandForOther(
2837 Instruction *Ext, TypePromotionTransaction &TPT,
2838 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2839 SmallVectorImpl<Instruction *> *Exts,
2840 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2841 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2842 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002843 }
2844
2845 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002846 static Value *zeroExtendOperandForOther(
2847 Instruction *Ext, TypePromotionTransaction &TPT,
2848 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2849 SmallVectorImpl<Instruction *> *Exts,
2850 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2851 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2852 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002853 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002854
2855public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002856 /// Type for the utility function that promotes the operand of Ext.
2857 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002858 InstrToOrigTy &PromotedInsts,
2859 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002860 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002861 SmallVectorImpl<Instruction *> *Truncs,
2862 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002863 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2864 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002865 /// \return NULL if no promotable action is possible with the current
2866 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002867 /// \p InsertedInsts keeps track of all the instructions inserted by the
2868 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002869 /// because we do not want to promote these instructions as CodeGenPrepare
2870 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2871 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002872 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002873 const TargetLowering &TLI,
2874 const InstrToOrigTy &PromotedInsts);
2875};
2876
2877bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002878 Type *ConsideredExtType,
2879 const InstrToOrigTy &PromotedInsts,
2880 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002881 // The promotion helper does not know how to deal with vector types yet.
2882 // To be able to fix that, we would need to fix the places where we
2883 // statically extend, e.g., constants and such.
2884 if (Inst->getType()->isVectorTy())
2885 return false;
2886
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002887 // We can always get through zext.
2888 if (isa<ZExtInst>(Inst))
2889 return true;
2890
2891 // sext(sext) is ok too.
2892 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002893 return true;
2894
2895 // We can get through binary operator, if it is legal. In other words, the
2896 // binary operator must have a nuw or nsw flag.
2897 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2898 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002899 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2900 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002901 return true;
2902
2903 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002904 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002905 if (!isa<TruncInst>(Inst))
2906 return false;
2907
2908 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002909 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002910 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002911 if (!OpndVal->getType()->isIntegerTy() ||
2912 OpndVal->getType()->getIntegerBitWidth() >
2913 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002914 return false;
2915
2916 // If the operand of the truncate is not an instruction, we will not have
2917 // any information on the dropped bits.
2918 // (Actually we could for constant but it is not worth the extra logic).
2919 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2920 if (!Opnd)
2921 return false;
2922
2923 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002924 // I.e., check that trunc just drops extended bits of the same kind of
2925 // the extension.
2926 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002927 const Type *OpndType;
2928 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002929 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2930 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002931 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2932 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002933 else
2934 return false;
2935
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002936 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002937 return Inst->getType()->getIntegerBitWidth() >=
2938 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002939}
2940
2941TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002942 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002943 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002944 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2945 "Unexpected instruction type");
2946 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2947 Type *ExtTy = Ext->getType();
2948 bool IsSExt = isa<SExtInst>(Ext);
2949 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002950 // get through.
2951 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002952 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002953 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002954
2955 // Do not promote if the operand has been added by codegenprepare.
2956 // Otherwise, it means we are undoing an optimization that is likely to be
2957 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002958 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002959 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002960
2961 // SExt or Trunc instructions.
2962 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002963 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2964 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002965 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002966
2967 // Regular instruction.
2968 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002969 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002970 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002971 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002972}
2973
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002974Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002975 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002976 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002977 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002978 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002979 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2980 // get through it and this method should not be called.
2981 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002982 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002983 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002984 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002985 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002986 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002987 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002988 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002989 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2990 TPT.replaceAllUsesWith(SExt, ZExt);
2991 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002992 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002993 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002994 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2995 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002996 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2997 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002998 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002999
3000 // Remove dead code.
3001 if (SExtOpnd->use_empty())
3002 TPT.eraseInstruction(SExtOpnd);
3003
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003004 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003005 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003006 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003007 if (ExtInst) {
3008 if (Exts)
3009 Exts->push_back(ExtInst);
3010 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3011 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003012 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003013 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003014
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003015 // At this point we have: ext ty opnd to ty.
3016 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3017 Value *NextVal = ExtInst->getOperand(0);
3018 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003019 return NextVal;
3020}
3021
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003022Value *TypePromotionHelper::promoteOperandForOther(
3023 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003024 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003025 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003026 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3027 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003028 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003029 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003030 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003031 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003032 if (!ExtOpnd->hasOneUse()) {
3033 // ExtOpnd will be promoted.
3034 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003035 // promoted version.
3036 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003037 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003038 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3039 ITrunc->removeFromParent();
3040 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003041 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003042 if (Truncs)
3043 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003044 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003045
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003046 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003047 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003048 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003049 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003050 }
3051
3052 // Get through the Instruction:
3053 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003054 // 2. Replace the uses of Ext by Inst.
3055 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003056
3057 // Remember the original type of the instruction before promotion.
3058 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003059 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3060 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003061 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003062 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003063 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003064 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003065 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003066 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003067
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003068 DEBUG(dbgs() << "Propagate Ext to operands\n");
3069 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003070 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003071 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3072 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3073 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003074 DEBUG(dbgs() << "No need to propagate\n");
3075 continue;
3076 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003077 // Check if we can statically extend the operand.
3078 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003079 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003080 DEBUG(dbgs() << "Statically extend\n");
3081 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3082 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3083 : Cst->getValue().zext(BitWidth);
3084 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003085 continue;
3086 }
3087 // UndefValue are typed, so we have to statically sign extend them.
3088 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003089 DEBUG(dbgs() << "Statically extend\n");
3090 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003091 continue;
3092 }
3093
3094 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003095 // Check if Ext was reused to extend an operand.
3096 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003097 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003098 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003099 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3100 : TPT.createZExt(Ext, Opnd, Ext->getType());
3101 if (!isa<Instruction>(ValForExtOpnd)) {
3102 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3103 continue;
3104 }
3105 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003106 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003107 if (Exts)
3108 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003109 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003110
3111 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003112 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3113 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003114 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003115 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003116 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003117 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003118 if (ExtForOpnd == Ext) {
3119 DEBUG(dbgs() << "Extension is useless now\n");
3120 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003121 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003122 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003123}
3124
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003125/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003126/// \p NewCost gives the cost of extension instructions created by the
3127/// promotion.
3128/// \p OldCost gives the cost of extension instructions before the promotion
3129/// plus the number of instructions that have been
3130/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003131/// \p PromotedOperand is the value that has been promoted.
3132/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003133bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003134 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3135 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3136 // The cost of the new extensions is greater than the cost of the
3137 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003138 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003139 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003140 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003141 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003142 return true;
3143 // The promotion is neutral but it may help folding the sign extension in
3144 // loads for instance.
3145 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003146 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003147}
3148
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003149/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003150/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003151/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003152/// If \p MovedAway is not NULL, it contains the information of whether or
3153/// not AddrInst has to be folded into the addressing mode on success.
3154/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3155/// because it has been moved away.
3156/// Thus AddrInst must not be added in the matched instructions.
3157/// This state can happen when AddrInst is a sext, since it may be moved away.
3158/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3159/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003160bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003161 unsigned Depth,
3162 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003163 // Avoid exponential behavior on extremely deep expression trees.
3164 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003165
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003166 // By default, all matched instructions stay in place.
3167 if (MovedAway)
3168 *MovedAway = false;
3169
Chandler Carruthc8925912013-01-05 02:09:22 +00003170 switch (Opcode) {
3171 case Instruction::PtrToInt:
3172 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003173 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003174 case Instruction::IntToPtr: {
3175 auto AS = AddrInst->getType()->getPointerAddressSpace();
3176 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003177 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003178 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003179 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003180 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003181 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003182 case Instruction::BitCast:
3183 // BitCast is always a noop, and we can handle it as long as it is
3184 // int->int or pointer->pointer (we don't want int<->fp or something).
3185 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3186 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3187 // Don't touch identity bitcasts. These were probably put here by LSR,
3188 // and we don't want to mess around with them. Assume it knows what it
3189 // is doing.
3190 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003191 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003192 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003193 case Instruction::AddrSpaceCast: {
3194 unsigned SrcAS
3195 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3196 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3197 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003198 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003199 return false;
3200 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003201 case Instruction::Add: {
3202 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3203 ExtAddrMode BackupAddrMode = AddrMode;
3204 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003205 // Start a transaction at this point.
3206 // The LHS may match but not the RHS.
3207 // Therefore, we need a higher level restoration point to undo partially
3208 // matched operation.
3209 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3210 TPT.getRestorationPoint();
3211
Sanjay Patelfc580a62015-09-21 23:03:16 +00003212 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3213 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003214 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003215
Chandler Carruthc8925912013-01-05 02:09:22 +00003216 // Restore the old addr mode info.
3217 AddrMode = BackupAddrMode;
3218 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003219 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003220
Chandler Carruthc8925912013-01-05 02:09:22 +00003221 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003222 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3223 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003224 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003225
Chandler Carruthc8925912013-01-05 02:09:22 +00003226 // Otherwise we definitely can't merge the ADD in.
3227 AddrMode = BackupAddrMode;
3228 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003229 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003230 break;
3231 }
3232 //case Instruction::Or:
3233 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3234 //break;
3235 case Instruction::Mul:
3236 case Instruction::Shl: {
3237 // Can only handle X*C and X << C.
3238 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003239 if (!RHS)
3240 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003241 int64_t Scale = RHS->getSExtValue();
3242 if (Opcode == Instruction::Shl)
3243 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003244
Sanjay Patelfc580a62015-09-21 23:03:16 +00003245 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003246 }
3247 case Instruction::GetElementPtr: {
3248 // Scan the GEP. We check it if it contains constant offsets and at most
3249 // one variable offset.
3250 int VariableOperand = -1;
3251 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003252
Chandler Carruthc8925912013-01-05 02:09:22 +00003253 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003254 gep_type_iterator GTI = gep_type_begin(AddrInst);
3255 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3256 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003257 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003258 unsigned Idx =
3259 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3260 ConstantOffset += SL->getElementOffset(Idx);
3261 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003262 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003263 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3264 ConstantOffset += CI->getSExtValue()*TypeSize;
3265 } else if (TypeSize) { // Scales of zero don't do anything.
3266 // We only allow one variable index at the moment.
3267 if (VariableOperand != -1)
3268 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003269
Chandler Carruthc8925912013-01-05 02:09:22 +00003270 // Remember the variable index.
3271 VariableOperand = i;
3272 VariableScale = TypeSize;
3273 }
3274 }
3275 }
Stephen Lin837bba12013-07-15 17:55:02 +00003276
Chandler Carruthc8925912013-01-05 02:09:22 +00003277 // A common case is for the GEP to only do a constant offset. In this case,
3278 // just add it to the disp field and check validity.
3279 if (VariableOperand == -1) {
3280 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003281 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003282 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003283 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003284 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003285 return true;
3286 }
3287 AddrMode.BaseOffs -= ConstantOffset;
3288 return false;
3289 }
3290
3291 // Save the valid addressing mode in case we can't match.
3292 ExtAddrMode BackupAddrMode = AddrMode;
3293 unsigned OldSize = AddrModeInsts.size();
3294
3295 // See if the scale and offset amount is valid for this target.
3296 AddrMode.BaseOffs += ConstantOffset;
3297
3298 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003299 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003300 // If it couldn't be matched, just stuff the value in a register.
3301 if (AddrMode.HasBaseReg) {
3302 AddrMode = BackupAddrMode;
3303 AddrModeInsts.resize(OldSize);
3304 return false;
3305 }
3306 AddrMode.HasBaseReg = true;
3307 AddrMode.BaseReg = AddrInst->getOperand(0);
3308 }
3309
3310 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003311 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003312 Depth)) {
3313 // If it couldn't be matched, try stuffing the base into a register
3314 // instead of matching it, and retrying the match of the scale.
3315 AddrMode = BackupAddrMode;
3316 AddrModeInsts.resize(OldSize);
3317 if (AddrMode.HasBaseReg)
3318 return false;
3319 AddrMode.HasBaseReg = true;
3320 AddrMode.BaseReg = AddrInst->getOperand(0);
3321 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003322 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003323 VariableScale, Depth)) {
3324 // If even that didn't work, bail.
3325 AddrMode = BackupAddrMode;
3326 AddrModeInsts.resize(OldSize);
3327 return false;
3328 }
3329 }
3330
3331 return true;
3332 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003333 case Instruction::SExt:
3334 case Instruction::ZExt: {
3335 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3336 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003337 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003338
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003339 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003340 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003341 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003342 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003343 if (!TPH)
3344 return false;
3345
3346 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3347 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003348 unsigned CreatedInstsCost = 0;
3349 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003350 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003351 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003352 // SExt has been moved away.
3353 // Thus either it will be rematched later in the recursive calls or it is
3354 // gone. Anyway, we must not fold it into the addressing mode at this point.
3355 // E.g.,
3356 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003357 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003358 // addr = gep base, idx
3359 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003360 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003361 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3362 // addr = gep base, op <- match
3363 if (MovedAway)
3364 *MovedAway = true;
3365
3366 assert(PromotedOperand &&
3367 "TypePromotionHelper should have filtered out those cases");
3368
3369 ExtAddrMode BackupAddrMode = AddrMode;
3370 unsigned OldSize = AddrModeInsts.size();
3371
Sanjay Patelfc580a62015-09-21 23:03:16 +00003372 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003373 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003374 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003375 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003376 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003377 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003378 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003379 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003380 AddrMode = BackupAddrMode;
3381 AddrModeInsts.resize(OldSize);
3382 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3383 TPT.rollback(LastKnownGood);
3384 return false;
3385 }
3386 return true;
3387 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003388 }
3389 return false;
3390}
3391
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003392/// If we can, try to add the value of 'Addr' into the current addressing mode.
3393/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3394/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3395/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003396///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003397bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003398 // Start a transaction at this point that we will rollback if the matching
3399 // fails.
3400 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3401 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003402 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3403 // Fold in immediates if legal for the target.
3404 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003405 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003406 return true;
3407 AddrMode.BaseOffs -= CI->getSExtValue();
3408 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3409 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003410 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003411 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003412 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003413 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003414 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003415 }
3416 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3417 ExtAddrMode BackupAddrMode = AddrMode;
3418 unsigned OldSize = AddrModeInsts.size();
3419
3420 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003421 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003422 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003423 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003424 // to check here.
3425 if (MovedAway)
3426 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003427 // Okay, it's possible to fold this. Check to see if it is actually
3428 // *profitable* to do so. We use a simple cost model to avoid increasing
3429 // register pressure too much.
3430 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003431 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003432 AddrModeInsts.push_back(I);
3433 return true;
3434 }
Stephen Lin837bba12013-07-15 17:55:02 +00003435
Chandler Carruthc8925912013-01-05 02:09:22 +00003436 // It isn't profitable to do this, roll back.
3437 //cerr << "NOT FOLDING: " << *I;
3438 AddrMode = BackupAddrMode;
3439 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003440 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003441 }
3442 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003443 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003444 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003445 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003446 } else if (isa<ConstantPointerNull>(Addr)) {
3447 // Null pointer gets folded without affecting the addressing mode.
3448 return true;
3449 }
3450
3451 // Worse case, the target should support [reg] addressing modes. :)
3452 if (!AddrMode.HasBaseReg) {
3453 AddrMode.HasBaseReg = true;
3454 AddrMode.BaseReg = Addr;
3455 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003456 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003457 return true;
3458 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003459 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003460 }
3461
3462 // If the base register is already taken, see if we can do [r+r].
3463 if (AddrMode.Scale == 0) {
3464 AddrMode.Scale = 1;
3465 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003466 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003467 return true;
3468 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003469 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003470 }
3471 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003472 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003473 return false;
3474}
3475
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003476/// Check to see if all uses of OpVal by the specified inline asm call are due
3477/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003478static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003479 const TargetMachine &TM) {
3480 const Function *F = CI->getParent()->getParent();
3481 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3482 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003483 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003484 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3485 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003486 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3487 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003488
Chandler Carruthc8925912013-01-05 02:09:22 +00003489 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003490 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003491
3492 // If this asm operand is our Value*, and if it isn't an indirect memory
3493 // operand, we can't fold it!
3494 if (OpInfo.CallOperandVal == OpVal &&
3495 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3496 !OpInfo.isIndirect))
3497 return false;
3498 }
3499
3500 return true;
3501}
3502
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003503/// Recursively walk all the uses of I until we find a memory use.
3504/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003505/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003506static bool FindAllMemoryUses(
3507 Instruction *I,
3508 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3509 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003510 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003511 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003512 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003513
Chandler Carruthc8925912013-01-05 02:09:22 +00003514 // If this is an obviously unfoldable instruction, bail out.
3515 if (!MightBeFoldableInst(I))
3516 return true;
3517
Philip Reamesac115ed2016-03-09 23:13:12 +00003518 const bool OptSize = I->getFunction()->optForSize();
3519
Chandler Carruthc8925912013-01-05 02:09:22 +00003520 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003521 for (Use &U : I->uses()) {
3522 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003523
Chandler Carruthcdf47882014-03-09 03:16:01 +00003524 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3525 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003526 continue;
3527 }
Stephen Lin837bba12013-07-15 17:55:02 +00003528
Chandler Carruthcdf47882014-03-09 03:16:01 +00003529 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3530 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003531 if (opNo == 0) return true; // Storing addr, not into addr.
3532 MemoryUses.push_back(std::make_pair(SI, opNo));
3533 continue;
3534 }
Stephen Lin837bba12013-07-15 17:55:02 +00003535
Chandler Carruthcdf47882014-03-09 03:16:01 +00003536 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003537 // If this is a cold call, we can sink the addressing calculation into
3538 // the cold path. See optimizeCallInst
3539 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3540 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003541
Chandler Carruthc8925912013-01-05 02:09:22 +00003542 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3543 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003544
Chandler Carruthc8925912013-01-05 02:09:22 +00003545 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003546 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003547 return true;
3548 continue;
3549 }
Stephen Lin837bba12013-07-15 17:55:02 +00003550
Eric Christopher11e4df72015-02-26 22:38:43 +00003551 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003552 return true;
3553 }
3554
3555 return false;
3556}
3557
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003558/// Return true if Val is already known to be live at the use site that we're
3559/// folding it into. If so, there is no cost to include it in the addressing
3560/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3561/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003562bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003563 Value *KnownLive2) {
3564 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003565 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003566 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003567
Chandler Carruthc8925912013-01-05 02:09:22 +00003568 // All values other than instructions and arguments (e.g. constants) are live.
3569 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003570
Chandler Carruthc8925912013-01-05 02:09:22 +00003571 // If Val is a constant sized alloca in the entry block, it is live, this is
3572 // true because it is just a reference to the stack/frame pointer, which is
3573 // live for the whole function.
3574 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3575 if (AI->isStaticAlloca())
3576 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003577
Chandler Carruthc8925912013-01-05 02:09:22 +00003578 // Check to see if this value is already used in the memory instruction's
3579 // block. If so, it's already live into the block at the very least, so we
3580 // can reasonably fold it.
3581 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3582}
3583
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003584/// It is possible for the addressing mode of the machine to fold the specified
3585/// instruction into a load or store that ultimately uses it.
3586/// However, the specified instruction has multiple uses.
3587/// Given this, it may actually increase register pressure to fold it
3588/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003589///
3590/// X = ...
3591/// Y = X+1
3592/// use(Y) -> nonload/store
3593/// Z = Y+1
3594/// load Z
3595///
3596/// In this case, Y has multiple uses, and can be folded into the load of Z
3597/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3598/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3599/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3600/// number of computations either.
3601///
3602/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3603/// X was live across 'load Z' for other reasons, we actually *would* want to
3604/// fold the addressing mode in the Z case. This would make Y die earlier.
3605bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003606isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003607 ExtAddrMode &AMAfter) {
3608 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003609
Chandler Carruthc8925912013-01-05 02:09:22 +00003610 // AMBefore is the addressing mode before this instruction was folded into it,
3611 // and AMAfter is the addressing mode after the instruction was folded. Get
3612 // the set of registers referenced by AMAfter and subtract out those
3613 // referenced by AMBefore: this is the set of values which folding in this
3614 // address extends the lifetime of.
3615 //
3616 // Note that there are only two potential values being referenced here,
3617 // BaseReg and ScaleReg (global addresses are always available, as are any
3618 // folded immediates).
3619 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003620
Chandler Carruthc8925912013-01-05 02:09:22 +00003621 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3622 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003623 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003624 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003625 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003626 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003627
3628 // If folding this instruction (and it's subexprs) didn't extend any live
3629 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003630 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003631 return true;
3632
Philip Reamesac115ed2016-03-09 23:13:12 +00003633 // If all uses of this instruction can have the address mode sunk into them,
3634 // we can remove the addressing mode and effectively trade one live register
3635 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003636 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003637 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3638 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003639 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003640 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003641
Chandler Carruthc8925912013-01-05 02:09:22 +00003642 // Now that we know that all uses of this instruction are part of a chain of
3643 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003644 // into a memory use, loop over each of these memory operation uses and see
3645 // if they could *actually* fold the instruction. The assumption is that
3646 // addressing modes are cheap and that duplicating the computation involved
3647 // many times is worthwhile, even on a fastpath. For sinking candidates
3648 // (i.e. cold call sites), this serves as a way to prevent excessive code
3649 // growth since most architectures have some reasonable small and fast way to
3650 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003651 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3652 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3653 Instruction *User = MemoryUses[i].first;
3654 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003655
Chandler Carruthc8925912013-01-05 02:09:22 +00003656 // Get the access type of this use. If the use isn't a pointer, we don't
3657 // know what it accesses.
3658 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003659 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3660 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003661 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003662 Type *AddressAccessTy = AddrTy->getElementType();
3663 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003664
Chandler Carruthc8925912013-01-05 02:09:22 +00003665 // Do a match against the root of this address, ignoring profitability. This
3666 // will tell us if the addressing mode for the memory operation will
3667 // *actually* cover the shared instruction.
3668 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003669 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3670 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003671 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003672 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003673 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003674 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003675 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003676 (void)Success; assert(Success && "Couldn't select *anything*?");
3677
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003678 // The match was to check the profitability, the changes made are not
3679 // part of the original matcher. Therefore, they should be dropped
3680 // otherwise the original matcher will not present the right state.
3681 TPT.rollback(LastKnownGood);
3682
Chandler Carruthc8925912013-01-05 02:09:22 +00003683 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003684 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003685 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003686
Chandler Carruthc8925912013-01-05 02:09:22 +00003687 MatchedAddrModeInsts.clear();
3688 }
Stephen Lin837bba12013-07-15 17:55:02 +00003689
Chandler Carruthc8925912013-01-05 02:09:22 +00003690 return true;
3691}
3692
3693} // end anonymous namespace
3694
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003695/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003696/// different basic block than BB.
3697static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3698 if (Instruction *I = dyn_cast<Instruction>(V))
3699 return I->getParent() != BB;
3700 return false;
3701}
3702
Philip Reamesac115ed2016-03-09 23:13:12 +00003703/// Sink addressing mode computation immediate before MemoryInst if doing so
3704/// can be done without increasing register pressure. The need for the
3705/// register pressure constraint means this can end up being an all or nothing
3706/// decision for all uses of the same addressing computation.
3707///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003708/// Load and Store Instructions often have addressing modes that can do
3709/// significant amounts of computation. As such, instruction selection will try
3710/// to get the load or store to do as much computation as possible for the
3711/// program. The problem is that isel can only see within a single block. As
3712/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003713///
3714/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003715/// operands. It's also used to sink addressing computations feeding into cold
3716/// call sites into their (cold) basic block.
3717///
3718/// The motivation for handling sinking into cold blocks is that doing so can
3719/// both enable other address mode sinking (by satisfying the register pressure
3720/// constraint above), and reduce register pressure globally (by removing the
3721/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003722bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003723 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003724 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003725
3726 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003727 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003728 SmallVector<Value*, 8> worklist;
3729 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003730 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003731
Owen Anderson8ba5f392010-11-27 08:15:55 +00003732 // Use a worklist to iteratively look through PHI nodes, and ensure that
3733 // the addressing mode obtained from the non-PHI roots of the graph
3734 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003735 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003736 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003737 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003738 SmallVector<Instruction*, 16> AddrModeInsts;
3739 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003740 TypePromotionTransaction TPT;
3741 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3742 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003743 while (!worklist.empty()) {
3744 Value *V = worklist.back();
3745 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003746
Owen Anderson8ba5f392010-11-27 08:15:55 +00003747 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003748 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003749 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003750 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003751 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003752
Owen Anderson8ba5f392010-11-27 08:15:55 +00003753 // For a PHI node, push all of its incoming values.
3754 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003755 for (Value *IncValue : P->incoming_values())
3756 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003757 continue;
3758 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003759
Philip Reamesac115ed2016-03-09 23:13:12 +00003760 // For non-PHIs, determine the addressing mode being computed. Note that
3761 // the result may differ depending on what other uses our candidate
3762 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003763 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003764 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003765 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003766 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003767
3768 // This check is broken into two cases with very similar code to avoid using
3769 // getNumUses() as much as possible. Some values have a lot of uses, so
3770 // calling getNumUses() unconditionally caused a significant compile-time
3771 // regression.
3772 if (!Consensus) {
3773 Consensus = V;
3774 AddrMode = NewAddrMode;
3775 AddrModeInsts = NewAddrModeInsts;
3776 continue;
3777 } else if (NewAddrMode == AddrMode) {
3778 if (!IsNumUsesConsensusValid) {
3779 NumUsesConsensus = Consensus->getNumUses();
3780 IsNumUsesConsensusValid = true;
3781 }
3782
3783 // Ensure that the obtained addressing mode is equivalent to that obtained
3784 // for all other roots of the PHI traversal. Also, when choosing one
3785 // such root as representative, select the one with the most uses in order
3786 // to keep the cost modeling heuristics in AddressingModeMatcher
3787 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003788 unsigned NumUses = V->getNumUses();
3789 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003790 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003791 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003792 AddrModeInsts = NewAddrModeInsts;
3793 }
3794 continue;
3795 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003796
Craig Topperc0196b12014-04-14 00:51:57 +00003797 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003798 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003799 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003800
Owen Anderson8ba5f392010-11-27 08:15:55 +00003801 // If the addressing mode couldn't be determined, or if multiple different
3802 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003803 if (!Consensus) {
3804 TPT.rollback(LastKnownGood);
3805 return false;
3806 }
3807 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003808
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003809 // Check to see if any of the instructions supersumed by this addr mode are
3810 // non-local to I's BB.
3811 bool AnyNonLocal = false;
3812 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003813 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003814 AnyNonLocal = true;
3815 break;
3816 }
3817 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003818
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003819 // If all the instructions matched are already in this BB, don't do anything.
3820 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003821 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003822 return false;
3823 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003824
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003825 // Insert this computation right after this user. Since our caller is
3826 // scanning from the top of the BB to the bottom, reuse of the expr are
3827 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003828 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003829
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003830 // Now that we determined the addressing expression we want to use and know
3831 // that we have to sink it into this block. Check to see if we have already
3832 // done this for some other load/store instr in this block. If so, reuse the
3833 // computation.
3834 Value *&SunkAddr = SunkAddrs[Addr];
3835 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003836 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003837 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003838 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003839 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003840 } else if (AddrSinkUsingGEPs ||
3841 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003842 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3843 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003844 // By default, we use the GEP-based method when AA is used later. This
3845 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3846 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003847 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003848 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003849 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003850
3851 // First, find the pointer.
3852 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3853 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003854 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003855 }
3856
3857 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3858 // We can't add more than one pointer together, nor can we scale a
3859 // pointer (both of which seem meaningless).
3860 if (ResultPtr || AddrMode.Scale != 1)
3861 return false;
3862
3863 ResultPtr = AddrMode.ScaledReg;
3864 AddrMode.Scale = 0;
3865 }
3866
3867 if (AddrMode.BaseGV) {
3868 if (ResultPtr)
3869 return false;
3870
3871 ResultPtr = AddrMode.BaseGV;
3872 }
3873
3874 // If the real base value actually came from an inttoptr, then the matcher
3875 // will look through it and provide only the integer value. In that case,
3876 // use it here.
3877 if (!ResultPtr && AddrMode.BaseReg) {
3878 ResultPtr =
3879 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003880 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003881 } else if (!ResultPtr && AddrMode.Scale == 1) {
3882 ResultPtr =
3883 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3884 AddrMode.Scale = 0;
3885 }
3886
3887 if (!ResultPtr &&
3888 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3889 SunkAddr = Constant::getNullValue(Addr->getType());
3890 } else if (!ResultPtr) {
3891 return false;
3892 } else {
3893 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003894 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3895 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003896
3897 // Start with the base register. Do this first so that subsequent address
3898 // matching finds it last, which will prevent it from trying to match it
3899 // as the scaled value in case it happens to be a mul. That would be
3900 // problematic if we've sunk a different mul for the scale, because then
3901 // we'd end up sinking both muls.
3902 if (AddrMode.BaseReg) {
3903 Value *V = AddrMode.BaseReg;
3904 if (V->getType() != IntPtrTy)
3905 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3906
3907 ResultIndex = V;
3908 }
3909
3910 // Add the scale value.
3911 if (AddrMode.Scale) {
3912 Value *V = AddrMode.ScaledReg;
3913 if (V->getType() == IntPtrTy) {
3914 // done.
3915 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3916 cast<IntegerType>(V->getType())->getBitWidth()) {
3917 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3918 } else {
3919 // It is only safe to sign extend the BaseReg if we know that the math
3920 // required to create it did not overflow before we extend it. Since
3921 // the original IR value was tossed in favor of a constant back when
3922 // the AddrMode was created we need to bail out gracefully if widths
3923 // do not match instead of extending it.
3924 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3925 if (I && (ResultIndex != AddrMode.BaseReg))
3926 I->eraseFromParent();
3927 return false;
3928 }
3929
3930 if (AddrMode.Scale != 1)
3931 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3932 "sunkaddr");
3933 if (ResultIndex)
3934 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3935 else
3936 ResultIndex = V;
3937 }
3938
3939 // Add in the Base Offset if present.
3940 if (AddrMode.BaseOffs) {
3941 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3942 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003943 // We need to add this separately from the scale above to help with
3944 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003945 if (ResultPtr->getType() != I8PtrTy)
3946 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003947 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003948 }
3949
3950 ResultIndex = V;
3951 }
3952
3953 if (!ResultIndex) {
3954 SunkAddr = ResultPtr;
3955 } else {
3956 if (ResultPtr->getType() != I8PtrTy)
3957 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003958 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003959 }
3960
3961 if (SunkAddr->getType() != Addr->getType())
3962 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3963 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003964 } else {
David Greene74e2d492010-01-05 01:27:11 +00003965 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003966 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003967 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003968 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003969
3970 // Start with the base register. Do this first so that subsequent address
3971 // matching finds it last, which will prevent it from trying to match it
3972 // as the scaled value in case it happens to be a mul. That would be
3973 // problematic if we've sunk a different mul for the scale, because then
3974 // we'd end up sinking both muls.
3975 if (AddrMode.BaseReg) {
3976 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003977 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003978 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003979 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003980 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003981 Result = V;
3982 }
3983
3984 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003985 if (AddrMode.Scale) {
3986 Value *V = AddrMode.ScaledReg;
3987 if (V->getType() == IntPtrTy) {
3988 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003989 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003990 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003991 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3992 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003993 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003994 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003995 // It is only safe to sign extend the BaseReg if we know that the math
3996 // required to create it did not overflow before we extend it. Since
3997 // the original IR value was tossed in favor of a constant back when
3998 // the AddrMode was created we need to bail out gracefully if widths
3999 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004000 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004001 if (I && (Result != AddrMode.BaseReg))
4002 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004003 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004004 }
4005 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004006 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4007 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004008 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004009 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004010 else
4011 Result = V;
4012 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004013
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004014 // Add in the BaseGV if present.
4015 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004016 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004017 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004018 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004019 else
4020 Result = V;
4021 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004022
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004023 // Add in the Base Offset if present.
4024 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004025 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004026 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004027 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004028 else
4029 Result = V;
4030 }
4031
Craig Topperc0196b12014-04-14 00:51:57 +00004032 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004033 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004034 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004035 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004036 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004037
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004038 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004039
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004040 // If we have no uses, recursively delete the value and all dead instructions
4041 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004042 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004043 // This can cause recursive deletion, which can invalidate our iterator.
4044 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004045 Value *CurValue = &*CurInstIterator;
4046 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004047 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004048
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004049 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004050
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004051 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004052 // If the iterator instruction was recursively deleted, start over at the
4053 // start of the block.
4054 CurInstIterator = BB->begin();
4055 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004056 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004057 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004058 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004059 return true;
4060}
4061
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004062/// If there are any memory operands, use OptimizeMemoryInst to sink their
4063/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004064bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004065 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004066
Eric Christopher11e4df72015-02-26 22:38:43 +00004067 const TargetRegisterInfo *TRI =
4068 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004069 TargetLowering::AsmOperandInfoVector TargetConstraints =
4070 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004071 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004072 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4073 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004074
Evan Cheng1da25002008-02-26 02:42:37 +00004075 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004076 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004077
Eli Friedman666bbe32008-02-26 18:37:49 +00004078 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4079 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004080 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004081 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004082 } else if (OpInfo.Type == InlineAsm::isInput)
4083 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004084 }
4085
4086 return MadeChange;
4087}
4088
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004089/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4090/// sign extensions.
4091static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4092 assert(!Inst->use_empty() && "Input must have at least one use");
4093 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4094 bool IsSExt = isa<SExtInst>(FirstUser);
4095 Type *ExtTy = FirstUser->getType();
4096 for (const User *U : Inst->users()) {
4097 const Instruction *UI = cast<Instruction>(U);
4098 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4099 return false;
4100 Type *CurTy = UI->getType();
4101 // Same input and output types: Same instruction after CSE.
4102 if (CurTy == ExtTy)
4103 continue;
4104
4105 // If IsSExt is true, we are in this situation:
4106 // a = Inst
4107 // b = sext ty1 a to ty2
4108 // c = sext ty1 a to ty3
4109 // Assuming ty2 is shorter than ty3, this could be turned into:
4110 // a = Inst
4111 // b = sext ty1 a to ty2
4112 // c = sext ty2 b to ty3
4113 // However, the last sext is not free.
4114 if (IsSExt)
4115 return false;
4116
4117 // This is a ZExt, maybe this is free to extend from one type to another.
4118 // In that case, we would not account for a different use.
4119 Type *NarrowTy;
4120 Type *LargeTy;
4121 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4122 CurTy->getScalarType()->getIntegerBitWidth()) {
4123 NarrowTy = CurTy;
4124 LargeTy = ExtTy;
4125 } else {
4126 NarrowTy = ExtTy;
4127 LargeTy = CurTy;
4128 }
4129
4130 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4131 return false;
4132 }
4133 // All uses are the same or can be derived from one another for free.
4134 return true;
4135}
4136
4137/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4138/// load instruction.
4139/// If an ext(load) can be formed, it is returned via \p LI for the load
4140/// and \p Inst for the extension.
4141/// Otherwise LI == nullptr and Inst == nullptr.
4142/// When some promotion happened, \p TPT contains the proper state to
4143/// revert them.
4144///
4145/// \return true when promoting was necessary to expose the ext(load)
4146/// opportunity, false otherwise.
4147///
4148/// Example:
4149/// \code
4150/// %ld = load i32* %addr
4151/// %add = add nuw i32 %ld, 4
4152/// %zext = zext i32 %add to i64
4153/// \endcode
4154/// =>
4155/// \code
4156/// %ld = load i32* %addr
4157/// %zext = zext i32 %ld to i64
4158/// %add = add nuw i64 %zext, 4
4159/// \encode
4160/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004161bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004162 LoadInst *&LI, Instruction *&Inst,
4163 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004164 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004165 // Iterate over all the extensions to see if one form an ext(load).
4166 for (auto I : Exts) {
4167 // Check if we directly have ext(load).
4168 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4169 Inst = I;
4170 // No promotion happened here.
4171 return false;
4172 }
4173 // Check whether or not we want to do any promotion.
4174 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4175 continue;
4176 // Get the action to perform the promotion.
4177 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004178 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004179 // Check if we can promote.
4180 if (!TPH)
4181 continue;
4182 // Save the current state.
4183 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4184 TPT.getRestorationPoint();
4185 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004186 unsigned NewCreatedInstsCost = 0;
4187 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004188 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004189 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4190 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004191 assert(PromotedVal &&
4192 "TypePromotionHelper should have filtered out those cases");
4193
4194 // We would be able to merge only one extension in a load.
4195 // Therefore, if we have more than 1 new extension we heuristically
4196 // cut this search path, because it means we degrade the code quality.
4197 // With exactly 2, the transformation is neutral, because we will merge
4198 // one extension but leave one. However, we optimistically keep going,
4199 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004200 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4201 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004202 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004203 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004204 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004205 // The promotion is not profitable, rollback to the previous state.
4206 TPT.rollback(LastKnownGood);
4207 continue;
4208 }
4209 // The promotion is profitable.
4210 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004211 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004212 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004213 // If we have created a new extension, i.e., now we have two
4214 // extensions. We must make sure one of them is merged with
4215 // the load, otherwise we may degrade the code quality.
4216 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4217 // Promotion happened.
4218 return true;
4219 // If this does not help to expose an ext(load) then, rollback.
4220 TPT.rollback(LastKnownGood);
4221 }
4222 // None of the extension can form an ext(load).
4223 LI = nullptr;
4224 Inst = nullptr;
4225 return false;
4226}
4227
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004228/// Move a zext or sext fed by a load into the same basic block as the load,
4229/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4230/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004231/// \p I[in/out] the extension may be modified during the process if some
4232/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004233///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004234bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004235 // ExtLoad formation infrastructure requires TLI to be effective.
4236 if (!TLI)
4237 return false;
4238
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004239 // Try to promote a chain of computation if it allows to form
4240 // an extended load.
4241 TypePromotionTransaction TPT;
4242 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4243 TPT.getRestorationPoint();
4244 SmallVector<Instruction *, 1> Exts;
4245 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004246 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004247 LoadInst *LI = nullptr;
4248 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004249 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004250 if (!LI || !I) {
4251 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4252 "the code must remain the same");
4253 I = OldExt;
4254 return false;
4255 }
Dan Gohman99429a02009-10-16 20:59:35 +00004256
4257 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004258 // Make the cheap checks first if we did not promote.
4259 // If we promoted, we need to check if it is indeed profitable.
4260 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004261 return false;
4262
Mehdi Amini44ede332015-07-09 02:09:04 +00004263 EVT VT = TLI->getValueType(*DL, I->getType());
4264 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004265
Dan Gohman99429a02009-10-16 20:59:35 +00004266 // If the load has other users and the truncate is not free, this probably
4267 // isn't worthwhile.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004268 if (!LI->hasOneUse() &&
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004269 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004270 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4271 I = OldExt;
4272 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004273 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004274 }
Dan Gohman99429a02009-10-16 20:59:35 +00004275
4276 // Check whether the target supports casts folded into loads.
4277 unsigned LType;
4278 if (isa<ZExtInst>(I))
4279 LType = ISD::ZEXTLOAD;
4280 else {
4281 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4282 LType = ISD::SEXTLOAD;
4283 }
Chandler Carruth0f139b42016-11-04 06:54:00 +00004284 if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004285 I = OldExt;
4286 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004287 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004288 }
Dan Gohman99429a02009-10-16 20:59:35 +00004289
4290 // Move the extend into the same block as the load, so that SelectionDAG
4291 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004292 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004293 I->removeFromParent();
4294 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004295 // CGP does not check if the zext would be speculatively executed when moved
4296 // to the same basic block as the load. Preserving its original location would
4297 // pessimize the debugging experience, as well as negatively impact the
4298 // quality of sample pgo. We don't want to use "line 0" as that has a
4299 // size cost in the line-table section and logically the zext can be seen as
4300 // part of the load. Therefore we conservatively reuse the same debug location
4301 // for the load and the zext.
4302 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004303 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004304 return true;
4305}
4306
Sanjay Patelfc580a62015-09-21 23:03:16 +00004307bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004308 BasicBlock *DefBB = I->getParent();
4309
Bob Wilsonff714f92010-09-21 21:44:14 +00004310 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004311 // other uses of the source with result of extension.
4312 Value *Src = I->getOperand(0);
4313 if (Src->hasOneUse())
4314 return false;
4315
Evan Cheng2011df42007-12-13 07:50:36 +00004316 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004317 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004318 return false;
4319
Evan Cheng7bc89422007-12-12 00:51:06 +00004320 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004321 // this block.
4322 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004323 return false;
4324
Evan Chengd3d80172007-12-05 23:58:20 +00004325 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004326 for (User *U : I->users()) {
4327 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004328
4329 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004330 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004331 if (UserBB == DefBB) continue;
4332 DefIsLiveOut = true;
4333 break;
4334 }
4335 if (!DefIsLiveOut)
4336 return false;
4337
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004338 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004339 for (User *U : Src->users()) {
4340 Instruction *UI = cast<Instruction>(U);
4341 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004342 if (UserBB == DefBB) continue;
4343 // Be conservative. We don't want this xform to end up introducing
4344 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004345 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004346 return false;
4347 }
4348
Evan Chengd3d80172007-12-05 23:58:20 +00004349 // InsertedTruncs - Only insert one trunc in each block once.
4350 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4351
4352 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004353 for (Use &U : Src->uses()) {
4354 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004355
4356 // Figure out which BB this ext is used in.
4357 BasicBlock *UserBB = User->getParent();
4358 if (UserBB == DefBB) continue;
4359
4360 // Both src and def are live in this block. Rewrite the use.
4361 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4362
4363 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004364 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004365 assert(InsertPt != UserBB->end());
4366 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004367 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004368 }
4369
4370 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004371 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004372 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004373 MadeChange = true;
4374 }
4375
4376 return MadeChange;
4377}
4378
Geoff Berry5256fca2015-11-20 22:34:39 +00004379// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4380// just after the load if the target can fold this into one extload instruction,
4381// with the hope of eliminating some of the other later "and" instructions using
4382// the loaded value. "and"s that are made trivially redundant by the insertion
4383// of the new "and" are removed by this function, while others (e.g. those whose
4384// path from the load goes through a phi) are left for isel to potentially
4385// remove.
4386//
4387// For example:
4388//
4389// b0:
4390// x = load i32
4391// ...
4392// b1:
4393// y = and x, 0xff
4394// z = use y
4395//
4396// becomes:
4397//
4398// b0:
4399// x = load i32
4400// x' = and x, 0xff
4401// ...
4402// b1:
4403// z = use x'
4404//
4405// whereas:
4406//
4407// b0:
4408// x1 = load i32
4409// ...
4410// b1:
4411// x2 = load i32
4412// ...
4413// b2:
4414// x = phi x1, x2
4415// y = and x, 0xff
4416//
4417// becomes (after a call to optimizeLoadExt for each load):
4418//
4419// b0:
4420// x1 = load i32
4421// x1' = and x1, 0xff
4422// ...
4423// b1:
4424// x2 = load i32
4425// x2' = and x2, 0xff
4426// ...
4427// b2:
4428// x = phi x1', x2'
4429// y = and x, 0xff
4430//
4431
4432bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4433
4434 if (!Load->isSimple() ||
4435 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4436 return false;
4437
4438 // Skip loads we've already transformed or have no reason to transform.
4439 if (Load->hasOneUse()) {
4440 User *LoadUser = *Load->user_begin();
4441 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4442 !dyn_cast<PHINode>(LoadUser))
4443 return false;
4444 }
4445
4446 // Look at all uses of Load, looking through phis, to determine how many bits
4447 // of the loaded value are needed.
4448 SmallVector<Instruction *, 8> WorkList;
4449 SmallPtrSet<Instruction *, 16> Visited;
4450 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4451 for (auto *U : Load->users())
4452 WorkList.push_back(cast<Instruction>(U));
4453
4454 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4455 unsigned BitWidth = LoadResultVT.getSizeInBits();
4456 APInt DemandBits(BitWidth, 0);
4457 APInt WidestAndBits(BitWidth, 0);
4458
4459 while (!WorkList.empty()) {
4460 Instruction *I = WorkList.back();
4461 WorkList.pop_back();
4462
4463 // Break use-def graph loops.
4464 if (!Visited.insert(I).second)
4465 continue;
4466
4467 // For a PHI node, push all of its users.
4468 if (auto *Phi = dyn_cast<PHINode>(I)) {
4469 for (auto *U : Phi->users())
4470 WorkList.push_back(cast<Instruction>(U));
4471 continue;
4472 }
4473
4474 switch (I->getOpcode()) {
4475 case llvm::Instruction::And: {
4476 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4477 if (!AndC)
4478 return false;
4479 APInt AndBits = AndC->getValue();
4480 DemandBits |= AndBits;
4481 // Keep track of the widest and mask we see.
4482 if (AndBits.ugt(WidestAndBits))
4483 WidestAndBits = AndBits;
4484 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4485 AndsToMaybeRemove.push_back(I);
4486 break;
4487 }
4488
4489 case llvm::Instruction::Shl: {
4490 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4491 if (!ShlC)
4492 return false;
4493 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4494 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4495 DemandBits |= ShlDemandBits;
4496 break;
4497 }
4498
4499 case llvm::Instruction::Trunc: {
4500 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4501 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4502 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4503 DemandBits |= TruncBits;
4504 break;
4505 }
4506
4507 default:
4508 return false;
4509 }
4510 }
4511
4512 uint32_t ActiveBits = DemandBits.getActiveBits();
4513 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4514 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4515 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4516 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4517 // followed by an AND.
4518 // TODO: Look into removing this restriction by fixing backends to either
4519 // return false for isLoadExtLegal for i1 or have them select this pattern to
4520 // a single instruction.
4521 //
4522 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4523 // mask, since these are the only ands that will be removed by isel.
4524 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4525 WidestAndBits != DemandBits)
4526 return false;
4527
4528 LLVMContext &Ctx = Load->getType()->getContext();
4529 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4530 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4531
4532 // Reject cases that won't be matched as extloads.
4533 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4534 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4535 return false;
4536
4537 IRBuilder<> Builder(Load->getNextNode());
4538 auto *NewAnd = dyn_cast<Instruction>(
4539 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4540
4541 // Replace all uses of load with new and (except for the use of load in the
4542 // new and itself).
4543 Load->replaceAllUsesWith(NewAnd);
4544 NewAnd->setOperand(0, Load);
4545
4546 // Remove any and instructions that are now redundant.
4547 for (auto *And : AndsToMaybeRemove)
4548 // Check that the and mask is the same as the one we decided to put on the
4549 // new and.
4550 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4551 And->replaceAllUsesWith(NewAnd);
4552 if (&*CurInstIterator == And)
4553 CurInstIterator = std::next(And->getIterator());
4554 And->eraseFromParent();
4555 ++NumAndUses;
4556 }
4557
4558 ++NumAndsAdded;
4559 return true;
4560}
4561
Sanjay Patel69a50a12015-10-19 21:59:12 +00004562/// Check if V (an operand of a select instruction) is an expensive instruction
4563/// that is only used once.
4564static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4565 auto *I = dyn_cast<Instruction>(V);
4566 // If it's safe to speculatively execute, then it should not have side
4567 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004568 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4569 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004570}
4571
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004572/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004573static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004574 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004575 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004576 // If even a predictable select is cheap, then a branch can't be cheaper.
4577 if (!TLI->isPredictableSelectExpensive())
4578 return false;
4579
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004580 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004581 // whether a select is better represented as a branch.
4582
4583 // If metadata tells us that the select condition is obviously predictable,
4584 // then we want to replace the select with a branch.
4585 uint64_t TrueWeight, FalseWeight;
4586 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4587 uint64_t Max = std::max(TrueWeight, FalseWeight);
4588 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004589 if (Sum != 0) {
4590 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4591 if (Probability > TLI->getPredictableBranchThreshold())
4592 return true;
4593 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004594 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004595
4596 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4597
Sanjay Patel4e652762015-09-28 22:14:51 +00004598 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4599 // comparison condition. If the compare has more than one use, there's
4600 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004601 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004602 return false;
4603
Sanjay Patel69a50a12015-10-19 21:59:12 +00004604 // If either operand of the select is expensive and only needed on one side
4605 // of the select, we should form a branch.
4606 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4607 sinkSelectOperand(TTI, SI->getFalseValue()))
4608 return true;
4609
4610 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004611}
4612
Dehao Chen9bbb9412016-09-12 20:23:28 +00004613/// If \p isTrue is true, return the true value of \p SI, otherwise return
4614/// false value of \p SI. If the true/false value of \p SI is defined by any
4615/// select instructions in \p Selects, look through the defining select
4616/// instruction until the true/false value is not defined in \p Selects.
4617static Value *getTrueOrFalseValue(
4618 SelectInst *SI, bool isTrue,
4619 const SmallPtrSet<const Instruction *, 2> &Selects) {
4620 Value *V;
4621
4622 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4623 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004624 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004625 "The condition of DefSI does not match with SI");
4626 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4627 }
4628 return V;
4629}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004630
Nadav Rotem9d832022012-09-02 12:10:19 +00004631/// If we have a SelectInst that will likely profit from branch prediction,
4632/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004633bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004634 // Find all consecutive select instructions that share the same condition.
4635 SmallVector<SelectInst *, 2> ASI;
4636 ASI.push_back(SI);
4637 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4638 It != SI->getParent()->end(); ++It) {
4639 SelectInst *I = dyn_cast<SelectInst>(&*It);
4640 if (I && SI->getCondition() == I->getCondition()) {
4641 ASI.push_back(I);
4642 } else {
4643 break;
4644 }
4645 }
4646
4647 SelectInst *LastSI = ASI.back();
4648 // Increment the current iterator to skip all the rest of select instructions
4649 // because they will be either "not lowered" or "all lowered" to branch.
4650 CurInstIterator = std::next(LastSI->getIterator());
4651
Nadav Rotem9d832022012-09-02 12:10:19 +00004652 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4653
4654 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004655 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4656 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004657 return false;
4658
Nadav Rotem9d832022012-09-02 12:10:19 +00004659 TargetLowering::SelectSupportKind SelectKind;
4660 if (VectorCond)
4661 SelectKind = TargetLowering::VectorMaskSelect;
4662 else if (SI->getType()->isVectorTy())
4663 SelectKind = TargetLowering::ScalarCondVectorVal;
4664 else
4665 SelectKind = TargetLowering::ScalarValSelect;
4666
Sanjay Pateld66607b2016-04-26 17:11:17 +00004667 if (TLI->isSelectSupported(SelectKind) &&
4668 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4669 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004670
4671 ModifiedDT = true;
4672
Sanjay Patel69a50a12015-10-19 21:59:12 +00004673 // Transform a sequence like this:
4674 // start:
4675 // %cmp = cmp uge i32 %a, %b
4676 // %sel = select i1 %cmp, i32 %c, i32 %d
4677 //
4678 // Into:
4679 // start:
4680 // %cmp = cmp uge i32 %a, %b
4681 // br i1 %cmp, label %select.true, label %select.false
4682 // select.true:
4683 // br label %select.end
4684 // select.false:
4685 // br label %select.end
4686 // select.end:
4687 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4688 //
4689 // In addition, we may sink instructions that produce %c or %d from
4690 // the entry block into the destination(s) of the new branch.
4691 // If the true or false blocks do not contain a sunken instruction, that
4692 // block and its branch may be optimized away. In that case, one side of the
4693 // first branch will point directly to select.end, and the corresponding PHI
4694 // predecessor block will be the start block.
4695
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004696 // First, we split the block containing the select into 2 blocks.
4697 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004698 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004699 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004700
Sanjay Patel69a50a12015-10-19 21:59:12 +00004701 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004702 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004703
4704 // These are the new basic blocks for the conditional branch.
4705 // At least one will become an actual new basic block.
4706 BasicBlock *TrueBlock = nullptr;
4707 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004708 BranchInst *TrueBranch = nullptr;
4709 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004710
4711 // Sink expensive instructions into the conditional blocks to avoid executing
4712 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004713 for (SelectInst *SI : ASI) {
4714 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4715 if (TrueBlock == nullptr) {
4716 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4717 EndBlock->getParent(), EndBlock);
4718 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4719 }
4720 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4721 TrueInst->moveBefore(TrueBranch);
4722 }
4723 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4724 if (FalseBlock == nullptr) {
4725 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4726 EndBlock->getParent(), EndBlock);
4727 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4728 }
4729 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4730 FalseInst->moveBefore(FalseBranch);
4731 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004732 }
4733
4734 // If there was nothing to sink, then arbitrarily choose the 'false' side
4735 // for a new input value to the PHI.
4736 if (TrueBlock == FalseBlock) {
4737 assert(TrueBlock == nullptr &&
4738 "Unexpected basic block transform while optimizing select");
4739
4740 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4741 EndBlock->getParent(), EndBlock);
4742 BranchInst::Create(EndBlock, FalseBlock);
4743 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004744
4745 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004746 // If we did not create a new block for one of the 'true' or 'false' paths
4747 // of the condition, it means that side of the branch goes to the end block
4748 // directly and the path originates from the start block from the point of
4749 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004750 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004751 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004752 TT = EndBlock;
4753 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004754 TrueBlock = StartBlock;
4755 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004756 TT = TrueBlock;
4757 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004758 FalseBlock = StartBlock;
4759 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004760 TT = TrueBlock;
4761 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004762 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004763 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004764
Dehao Chen9bbb9412016-09-12 20:23:28 +00004765 SmallPtrSet<const Instruction *, 2> INS;
4766 INS.insert(ASI.begin(), ASI.end());
4767 // Use reverse iterator because later select may use the value of the
4768 // earlier select, and we need to propagate value through earlier select
4769 // to get the PHI operand.
4770 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4771 SelectInst *SI = *It;
4772 // The select itself is replaced with a PHI Node.
4773 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4774 PN->takeName(SI);
4775 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4776 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004777
Dehao Chen9bbb9412016-09-12 20:23:28 +00004778 SI->replaceAllUsesWith(PN);
4779 SI->eraseFromParent();
4780 INS.erase(SI);
4781 ++NumSelectsExpanded;
4782 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004783
4784 // Instruct OptimizeBlock to skip to the next block.
4785 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004786 return true;
4787}
4788
Benjamin Kramer573ff362014-03-01 17:24:40 +00004789static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004790 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4791 int SplatElem = -1;
4792 for (unsigned i = 0; i < Mask.size(); ++i) {
4793 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4794 return false;
4795 SplatElem = Mask[i];
4796 }
4797
4798 return true;
4799}
4800
4801/// Some targets have expensive vector shifts if the lanes aren't all the same
4802/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4803/// it's often worth sinking a shufflevector splat down to its use so that
4804/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004805bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004806 BasicBlock *DefBB = SVI->getParent();
4807
4808 // Only do this xform if variable vector shifts are particularly expensive.
4809 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4810 return false;
4811
4812 // We only expect better codegen by sinking a shuffle if we can recognise a
4813 // constant splat.
4814 if (!isBroadcastShuffle(SVI))
4815 return false;
4816
4817 // InsertedShuffles - Only insert a shuffle in each block once.
4818 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4819
4820 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004821 for (User *U : SVI->users()) {
4822 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004823
4824 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004825 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004826 if (UserBB == DefBB) continue;
4827
4828 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004829 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004830
4831 // Everything checks out, sink the shuffle if the user's block doesn't
4832 // already have a copy.
4833 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4834
4835 if (!InsertedShuffle) {
4836 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004837 assert(InsertPt != UserBB->end());
4838 InsertedShuffle =
4839 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4840 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004841 }
4842
Chandler Carruthcdf47882014-03-09 03:16:01 +00004843 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004844 MadeChange = true;
4845 }
4846
4847 // If we removed all uses, nuke the shuffle.
4848 if (SVI->use_empty()) {
4849 SVI->eraseFromParent();
4850 MadeChange = true;
4851 }
4852
4853 return MadeChange;
4854}
4855
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004856bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4857 if (!TLI || !DL)
4858 return false;
4859
4860 Value *Cond = SI->getCondition();
4861 Type *OldType = Cond->getType();
4862 LLVMContext &Context = Cond->getContext();
4863 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4864 unsigned RegWidth = RegType.getSizeInBits();
4865
4866 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4867 return false;
4868
4869 // If the register width is greater than the type width, expand the condition
4870 // of the switch instruction and each case constant to the width of the
4871 // register. By widening the type of the switch condition, subsequent
4872 // comparisons (for case comparisons) will not need to be extended to the
4873 // preferred register width, so we will potentially eliminate N-1 extends,
4874 // where N is the number of cases in the switch.
4875 auto *NewType = Type::getIntNTy(Context, RegWidth);
4876
4877 // Zero-extend the switch condition and case constants unless the switch
4878 // condition is a function argument that is already being sign-extended.
4879 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4880 // everything instead.
4881 Instruction::CastOps ExtType = Instruction::ZExt;
4882 if (auto *Arg = dyn_cast<Argument>(Cond))
4883 if (Arg->hasSExtAttr())
4884 ExtType = Instruction::SExt;
4885
4886 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4887 ExtInst->insertBefore(SI);
4888 SI->setCondition(ExtInst);
4889 for (SwitchInst::CaseIt Case : SI->cases()) {
4890 APInt NarrowConst = Case.getCaseValue()->getValue();
4891 APInt WideConst = (ExtType == Instruction::ZExt) ?
4892 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4893 Case.setValue(ConstantInt::get(Context, WideConst));
4894 }
4895
4896 return true;
4897}
4898
Quentin Colombetc32615d2014-10-31 17:52:53 +00004899namespace {
4900/// \brief Helper class to promote a scalar operation to a vector one.
4901/// This class is used to move downward extractelement transition.
4902/// E.g.,
4903/// a = vector_op <2 x i32>
4904/// b = extractelement <2 x i32> a, i32 0
4905/// c = scalar_op b
4906/// store c
4907///
4908/// =>
4909/// a = vector_op <2 x i32>
4910/// c = vector_op a (equivalent to scalar_op on the related lane)
4911/// * d = extractelement <2 x i32> c, i32 0
4912/// * store d
4913/// Assuming both extractelement and store can be combine, we get rid of the
4914/// transition.
4915class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004916 /// DataLayout associated with the current module.
4917 const DataLayout &DL;
4918
Quentin Colombetc32615d2014-10-31 17:52:53 +00004919 /// Used to perform some checks on the legality of vector operations.
4920 const TargetLowering &TLI;
4921
4922 /// Used to estimated the cost of the promoted chain.
4923 const TargetTransformInfo &TTI;
4924
4925 /// The transition being moved downwards.
4926 Instruction *Transition;
4927 /// The sequence of instructions to be promoted.
4928 SmallVector<Instruction *, 4> InstsToBePromoted;
4929 /// Cost of combining a store and an extract.
4930 unsigned StoreExtractCombineCost;
4931 /// Instruction that will be combined with the transition.
4932 Instruction *CombineInst;
4933
4934 /// \brief The instruction that represents the current end of the transition.
4935 /// Since we are faking the promotion until we reach the end of the chain
4936 /// of computation, we need a way to get the current end of the transition.
4937 Instruction *getEndOfTransition() const {
4938 if (InstsToBePromoted.empty())
4939 return Transition;
4940 return InstsToBePromoted.back();
4941 }
4942
4943 /// \brief Return the index of the original value in the transition.
4944 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4945 /// c, is at index 0.
4946 unsigned getTransitionOriginalValueIdx() const {
4947 assert(isa<ExtractElementInst>(Transition) &&
4948 "Other kind of transitions are not supported yet");
4949 return 0;
4950 }
4951
4952 /// \brief Return the index of the index in the transition.
4953 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4954 /// is at index 1.
4955 unsigned getTransitionIdx() const {
4956 assert(isa<ExtractElementInst>(Transition) &&
4957 "Other kind of transitions are not supported yet");
4958 return 1;
4959 }
4960
4961 /// \brief Get the type of the transition.
4962 /// This is the type of the original value.
4963 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4964 /// transition is <2 x i32>.
4965 Type *getTransitionType() const {
4966 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4967 }
4968
4969 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4970 /// I.e., we have the following sequence:
4971 /// Def = Transition <ty1> a to <ty2>
4972 /// b = ToBePromoted <ty2> Def, ...
4973 /// =>
4974 /// b = ToBePromoted <ty1> a, ...
4975 /// Def = Transition <ty1> ToBePromoted to <ty2>
4976 void promoteImpl(Instruction *ToBePromoted);
4977
4978 /// \brief Check whether or not it is profitable to promote all the
4979 /// instructions enqueued to be promoted.
4980 bool isProfitableToPromote() {
4981 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4982 unsigned Index = isa<ConstantInt>(ValIdx)
4983 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4984 : -1;
4985 Type *PromotedType = getTransitionType();
4986
4987 StoreInst *ST = cast<StoreInst>(CombineInst);
4988 unsigned AS = ST->getPointerAddressSpace();
4989 unsigned Align = ST->getAlignment();
4990 // Check if this store is supported.
4991 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004992 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4993 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004994 // If this is not supported, there is no way we can combine
4995 // the extract with the store.
4996 return false;
4997 }
4998
4999 // The scalar chain of computation has to pay for the transition
5000 // scalar to vector.
5001 // The vector chain has to account for the combining cost.
5002 uint64_t ScalarCost =
5003 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5004 uint64_t VectorCost = StoreExtractCombineCost;
5005 for (const auto &Inst : InstsToBePromoted) {
5006 // Compute the cost.
5007 // By construction, all instructions being promoted are arithmetic ones.
5008 // Moreover, one argument is a constant that can be viewed as a splat
5009 // constant.
5010 Value *Arg0 = Inst->getOperand(0);
5011 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5012 isa<ConstantFP>(Arg0);
5013 TargetTransformInfo::OperandValueKind Arg0OVK =
5014 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5015 : TargetTransformInfo::OK_AnyValue;
5016 TargetTransformInfo::OperandValueKind Arg1OVK =
5017 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5018 : TargetTransformInfo::OK_AnyValue;
5019 ScalarCost += TTI.getArithmeticInstrCost(
5020 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5021 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5022 Arg0OVK, Arg1OVK);
5023 }
5024 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5025 << ScalarCost << "\nVector: " << VectorCost << '\n');
5026 return ScalarCost > VectorCost;
5027 }
5028
5029 /// \brief Generate a constant vector with \p Val with the same
5030 /// number of elements as the transition.
5031 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005032 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005033 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5034 /// otherwise we generate a vector with as many undef as possible:
5035 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5036 /// used at the index of the extract.
5037 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5038 unsigned ExtractIdx = UINT_MAX;
5039 if (!UseSplat) {
5040 // If we cannot determine where the constant must be, we have to
5041 // use a splat constant.
5042 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5043 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5044 ExtractIdx = CstVal->getSExtValue();
5045 else
5046 UseSplat = true;
5047 }
5048
5049 unsigned End = getTransitionType()->getVectorNumElements();
5050 if (UseSplat)
5051 return ConstantVector::getSplat(End, Val);
5052
5053 SmallVector<Constant *, 4> ConstVec;
5054 UndefValue *UndefVal = UndefValue::get(Val->getType());
5055 for (unsigned Idx = 0; Idx != End; ++Idx) {
5056 if (Idx == ExtractIdx)
5057 ConstVec.push_back(Val);
5058 else
5059 ConstVec.push_back(UndefVal);
5060 }
5061 return ConstantVector::get(ConstVec);
5062 }
5063
5064 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5065 /// in \p Use can trigger undefined behavior.
5066 static bool canCauseUndefinedBehavior(const Instruction *Use,
5067 unsigned OperandIdx) {
5068 // This is not safe to introduce undef when the operand is on
5069 // the right hand side of a division-like instruction.
5070 if (OperandIdx != 1)
5071 return false;
5072 switch (Use->getOpcode()) {
5073 default:
5074 return false;
5075 case Instruction::SDiv:
5076 case Instruction::UDiv:
5077 case Instruction::SRem:
5078 case Instruction::URem:
5079 return true;
5080 case Instruction::FDiv:
5081 case Instruction::FRem:
5082 return !Use->hasNoNaNs();
5083 }
5084 llvm_unreachable(nullptr);
5085 }
5086
5087public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005088 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5089 const TargetTransformInfo &TTI, Instruction *Transition,
5090 unsigned CombineCost)
5091 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005092 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5093 assert(Transition && "Do not know how to promote null");
5094 }
5095
5096 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5097 bool canPromote(const Instruction *ToBePromoted) const {
5098 // We could support CastInst too.
5099 return isa<BinaryOperator>(ToBePromoted);
5100 }
5101
5102 /// \brief Check if it is profitable to promote \p ToBePromoted
5103 /// by moving downward the transition through.
5104 bool shouldPromote(const Instruction *ToBePromoted) const {
5105 // Promote only if all the operands can be statically expanded.
5106 // Indeed, we do not want to introduce any new kind of transitions.
5107 for (const Use &U : ToBePromoted->operands()) {
5108 const Value *Val = U.get();
5109 if (Val == getEndOfTransition()) {
5110 // If the use is a division and the transition is on the rhs,
5111 // we cannot promote the operation, otherwise we may create a
5112 // division by zero.
5113 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5114 return false;
5115 continue;
5116 }
5117 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5118 !isa<ConstantFP>(Val))
5119 return false;
5120 }
5121 // Check that the resulting operation is legal.
5122 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5123 if (!ISDOpcode)
5124 return false;
5125 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005126 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005127 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005128 }
5129
5130 /// \brief Check whether or not \p Use can be combined
5131 /// with the transition.
5132 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5133 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5134
5135 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5136 void enqueueForPromotion(Instruction *ToBePromoted) {
5137 InstsToBePromoted.push_back(ToBePromoted);
5138 }
5139
5140 /// \brief Set the instruction that will be combined with the transition.
5141 void recordCombineInstruction(Instruction *ToBeCombined) {
5142 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5143 CombineInst = ToBeCombined;
5144 }
5145
5146 /// \brief Promote all the instructions enqueued for promotion if it is
5147 /// is profitable.
5148 /// \return True if the promotion happened, false otherwise.
5149 bool promote() {
5150 // Check if there is something to promote.
5151 // Right now, if we do not have anything to combine with,
5152 // we assume the promotion is not profitable.
5153 if (InstsToBePromoted.empty() || !CombineInst)
5154 return false;
5155
5156 // Check cost.
5157 if (!StressStoreExtract && !isProfitableToPromote())
5158 return false;
5159
5160 // Promote.
5161 for (auto &ToBePromoted : InstsToBePromoted)
5162 promoteImpl(ToBePromoted);
5163 InstsToBePromoted.clear();
5164 return true;
5165 }
5166};
5167} // End of anonymous namespace.
5168
5169void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5170 // At this point, we know that all the operands of ToBePromoted but Def
5171 // can be statically promoted.
5172 // For Def, we need to use its parameter in ToBePromoted:
5173 // b = ToBePromoted ty1 a
5174 // Def = Transition ty1 b to ty2
5175 // Move the transition down.
5176 // 1. Replace all uses of the promoted operation by the transition.
5177 // = ... b => = ... Def.
5178 assert(ToBePromoted->getType() == Transition->getType() &&
5179 "The type of the result of the transition does not match "
5180 "the final type");
5181 ToBePromoted->replaceAllUsesWith(Transition);
5182 // 2. Update the type of the uses.
5183 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5184 Type *TransitionTy = getTransitionType();
5185 ToBePromoted->mutateType(TransitionTy);
5186 // 3. Update all the operands of the promoted operation with promoted
5187 // operands.
5188 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5189 for (Use &U : ToBePromoted->operands()) {
5190 Value *Val = U.get();
5191 Value *NewVal = nullptr;
5192 if (Val == Transition)
5193 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5194 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5195 isa<ConstantFP>(Val)) {
5196 // Use a splat constant if it is not safe to use undef.
5197 NewVal = getConstantVector(
5198 cast<Constant>(Val),
5199 isa<UndefValue>(Val) ||
5200 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5201 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005202 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5203 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005204 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5205 }
5206 Transition->removeFromParent();
5207 Transition->insertAfter(ToBePromoted);
5208 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5209}
5210
5211/// Some targets can do store(extractelement) with one instruction.
5212/// Try to push the extractelement towards the stores when the target
5213/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005214bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005215 unsigned CombineCost = UINT_MAX;
5216 if (DisableStoreExtract || !TLI ||
5217 (!StressStoreExtract &&
5218 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5219 Inst->getOperand(1), CombineCost)))
5220 return false;
5221
5222 // At this point we know that Inst is a vector to scalar transition.
5223 // Try to move it down the def-use chain, until:
5224 // - We can combine the transition with its single use
5225 // => we got rid of the transition.
5226 // - We escape the current basic block
5227 // => we would need to check that we are moving it at a cheaper place and
5228 // we do not do that for now.
5229 BasicBlock *Parent = Inst->getParent();
5230 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005231 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005232 // If the transition has more than one use, assume this is not going to be
5233 // beneficial.
5234 while (Inst->hasOneUse()) {
5235 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5236 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5237
5238 if (ToBePromoted->getParent() != Parent) {
5239 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5240 << ToBePromoted->getParent()->getName()
5241 << ") than the transition (" << Parent->getName() << ").\n");
5242 return false;
5243 }
5244
5245 if (VPH.canCombine(ToBePromoted)) {
5246 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5247 << "will be combined with: " << *ToBePromoted << '\n');
5248 VPH.recordCombineInstruction(ToBePromoted);
5249 bool Changed = VPH.promote();
5250 NumStoreExtractExposed += Changed;
5251 return Changed;
5252 }
5253
5254 DEBUG(dbgs() << "Try promoting.\n");
5255 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5256 return false;
5257
5258 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5259
5260 VPH.enqueueForPromotion(ToBePromoted);
5261 Inst = ToBePromoted;
5262 }
5263 return false;
5264}
5265
Sanjay Patelfc580a62015-09-21 23:03:16 +00005266bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005267 // Bail out if we inserted the instruction to prevent optimizations from
5268 // stepping on each other's toes.
5269 if (InsertedInsts.count(I))
5270 return false;
5271
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005272 if (PHINode *P = dyn_cast<PHINode>(I)) {
5273 // It is possible for very late stage optimizations (such as SimplifyCFG)
5274 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5275 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005276 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005277 P->replaceAllUsesWith(V);
5278 P->eraseFromParent();
5279 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005280 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005281 }
Chris Lattneree588de2011-01-15 07:29:01 +00005282 return false;
5283 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005284
Chris Lattneree588de2011-01-15 07:29:01 +00005285 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005286 // If the source of the cast is a constant, then this should have
5287 // already been constant folded. The only reason NOT to constant fold
5288 // it is if something (e.g. LSR) was careful to place the constant
5289 // evaluation in a block other than then one that uses it (e.g. to hoist
5290 // the address of globals out of a loop). If this is the case, we don't
5291 // want to forward-subst the cast.
5292 if (isa<Constant>(CI->getOperand(0)))
5293 return false;
5294
Mehdi Amini44ede332015-07-09 02:09:04 +00005295 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005296 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005297
Chris Lattneree588de2011-01-15 07:29:01 +00005298 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005299 /// Sink a zext or sext into its user blocks if the target type doesn't
5300 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005301 if (TLI &&
5302 TLI->getTypeAction(CI->getContext(),
5303 TLI->getValueType(*DL, CI->getType())) ==
5304 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005305 return SinkCast(CI);
5306 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005307 bool MadeChange = moveExtToFormExtLoad(I);
5308 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005309 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005310 }
Chris Lattneree588de2011-01-15 07:29:01 +00005311 return false;
5312 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005313
Chris Lattneree588de2011-01-15 07:29:01 +00005314 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005315 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005316 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005317
Chris Lattneree588de2011-01-15 07:29:01 +00005318 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005319 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005320 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005321 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005322 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005323 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5324 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005325 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005326 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005327 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005328
Chris Lattneree588de2011-01-15 07:29:01 +00005329 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005330 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005331 if (TLI) {
5332 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005333 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005334 SI->getOperand(0)->getType(), AS);
5335 }
Chris Lattneree588de2011-01-15 07:29:01 +00005336 return false;
5337 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005338
Yi Jiangd069f632014-04-21 19:34:27 +00005339 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5340
5341 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5342 BinOp->getOpcode() == Instruction::LShr)) {
5343 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5344 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005345 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005346
5347 return false;
5348 }
5349
Chris Lattneree588de2011-01-15 07:29:01 +00005350 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005351 if (GEPI->hasAllZeroIndices()) {
5352 /// The GEP operand must be a pointer, so must its result -> BitCast
5353 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5354 GEPI->getName(), GEPI);
5355 GEPI->replaceAllUsesWith(NC);
5356 GEPI->eraseFromParent();
5357 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005358 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005359 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005360 }
Chris Lattneree588de2011-01-15 07:29:01 +00005361 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005362 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005363
Chris Lattneree588de2011-01-15 07:29:01 +00005364 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005365 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005366
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005367 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005368 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005369
Tim Northoveraeb8e062014-02-19 10:02:43 +00005370 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005371 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005372
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005373 if (auto *Switch = dyn_cast<SwitchInst>(I))
5374 return optimizeSwitchInst(Switch);
5375
Quentin Colombetc32615d2014-10-31 17:52:53 +00005376 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005377 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005378
Chris Lattneree588de2011-01-15 07:29:01 +00005379 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005380}
5381
James Molloyf01488e2016-01-15 09:20:19 +00005382/// Given an OR instruction, check to see if this is a bitreverse
5383/// idiom. If so, insert the new intrinsic and return true.
5384static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5385 const TargetLowering &TLI) {
5386 if (!I.getType()->isIntegerTy() ||
5387 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5388 TLI.getValueType(DL, I.getType(), true)))
5389 return false;
5390
5391 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005392 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005393 return false;
5394 Instruction *LastInst = Insts.back();
5395 I.replaceAllUsesWith(LastInst);
5396 RecursivelyDeleteTriviallyDeadInstructions(&I);
5397 return true;
5398}
5399
Chris Lattnerf2836d12007-03-31 04:06:36 +00005400// In this pass we look for GEP and cast instructions that are used
5401// across basic blocks and rewrite them to improve basic-block-at-a-time
5402// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005403bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005404 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005405 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005406
Chris Lattner7a277142011-01-15 07:14:54 +00005407 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005408 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005409 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005410 if (ModifiedDT)
5411 return true;
5412 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005413
James Molloyf01488e2016-01-15 09:20:19 +00005414 bool MadeBitReverse = true;
5415 while (TLI && MadeBitReverse) {
5416 MadeBitReverse = false;
5417 for (auto &I : reverse(BB)) {
5418 if (makeBitReverse(I, *DL, *TLI)) {
5419 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005420 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005421 break;
5422 }
5423 }
5424 }
James Molloy3ef84c42016-01-15 10:36:01 +00005425 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005426
Chris Lattnerf2836d12007-03-31 04:06:36 +00005427 return MadeChange;
5428}
Devang Patel53771ba2011-08-18 00:50:51 +00005429
5430// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005431// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005432// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005433bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005434 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005435 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005436 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005437 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005438 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005439 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005440 // Leave dbg.values that refer to an alloca alone. These
5441 // instrinsics describe the address of a variable (= the alloca)
5442 // being taken. They should not be moved next to the alloca
5443 // (and to the beginning of the scope), but rather stay close to
5444 // where said address is used.
5445 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005446 PrevNonDbgInst = Insn;
5447 continue;
5448 }
5449
5450 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5451 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005452 // If VI is a phi in a block with an EHPad terminator, we can't insert
5453 // after it.
5454 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5455 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005456 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5457 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005458 if (isa<PHINode>(VI))
5459 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5460 else
5461 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005462 MadeChange = true;
5463 ++NumDbgValueMoved;
5464 }
5465 }
5466 }
5467 return MadeChange;
5468}
Tim Northovercea0abb2014-03-29 08:22:29 +00005469
5470// If there is a sequence that branches based on comparing a single bit
5471// against zero that can be combined into a single instruction, and the
5472// target supports folding these into a single instruction, sink the
5473// mask and compare into the branch uses. Do this before OptimizeBlock ->
5474// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5475// searched for.
5476bool CodeGenPrepare::sinkAndCmp(Function &F) {
5477 if (!EnableAndCmpSinking)
5478 return false;
5479 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5480 return false;
5481 bool MadeChange = false;
Sanjay Patel892f1672016-04-11 20:13:44 +00005482 for (BasicBlock &BB : F) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005483 // Does this BB end with the following?
5484 // %andVal = and %val, #single-bit-set
5485 // %icmpVal = icmp %andResult, 0
5486 // br i1 %cmpVal label %dest1, label %dest2"
Sanjay Patel892f1672016-04-11 20:13:44 +00005487 BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
Tim Northovercea0abb2014-03-29 08:22:29 +00005488 if (!Brcc || !Brcc->isConditional())
5489 continue;
5490 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005491 if (!Cmp || Cmp->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005492 continue;
5493 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5494 if (!Zero || !Zero->isZero())
5495 continue;
5496 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005497 if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005498 continue;
5499 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5500 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5501 continue;
Sanjay Patel892f1672016-04-11 20:13:44 +00005502 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
Tim Northovercea0abb2014-03-29 08:22:29 +00005503
5504 // Push the "and; icmp" for any users that are conditional branches.
5505 // Since there can only be one branch use per BB, we don't need to keep
5506 // track of which BBs we insert into.
Sanjay Patel892f1672016-04-11 20:13:44 +00005507 for (Use &TheUse : Cmp->uses()) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005508 // Find brcc use.
Sanjay Patel892f1672016-04-11 20:13:44 +00005509 BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
Tim Northovercea0abb2014-03-29 08:22:29 +00005510 if (!BrccUser || !BrccUser->isConditional())
5511 continue;
5512 BasicBlock *UserBB = BrccUser->getParent();
Sanjay Patel892f1672016-04-11 20:13:44 +00005513 if (UserBB == &BB) continue;
Tim Northovercea0abb2014-03-29 08:22:29 +00005514 DEBUG(dbgs() << "found Brcc use\n");
5515
5516 // Sink the "and; icmp" to use.
5517 MadeChange = true;
5518 BinaryOperator *NewAnd =
5519 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5520 BrccUser);
5521 CmpInst *NewCmp =
5522 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5523 "", BrccUser);
5524 TheUse = NewCmp;
5525 ++NumAndCmpsMoved;
5526 DEBUG(BrccUser->getParent()->dump());
5527 }
5528 }
5529 return MadeChange;
5530}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005531
5532/// \brief Scale down both weights to fit into uint32_t.
5533static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5534 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5535 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5536 NewTrue = NewTrue / Scale;
5537 NewFalse = NewFalse / Scale;
5538}
5539
5540/// \brief Some targets prefer to split a conditional branch like:
5541/// \code
5542/// %0 = icmp ne i32 %a, 0
5543/// %1 = icmp ne i32 %b, 0
5544/// %or.cond = or i1 %0, %1
5545/// br i1 %or.cond, label %TrueBB, label %FalseBB
5546/// \endcode
5547/// into multiple branch instructions like:
5548/// \code
5549/// bb1:
5550/// %0 = icmp ne i32 %a, 0
5551/// br i1 %0, label %TrueBB, label %bb2
5552/// bb2:
5553/// %1 = icmp ne i32 %b, 0
5554/// br i1 %1, label %TrueBB, label %FalseBB
5555/// \endcode
5556/// This usually allows instruction selection to do even further optimizations
5557/// and combine the compare with the branch instruction. Currently this is
5558/// applied for targets which have "cheap" jump instructions.
5559///
5560/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5561///
5562bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005563 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005564 return false;
5565
5566 bool MadeChange = false;
5567 for (auto &BB : F) {
5568 // Does this BB end with the following?
5569 // %cond1 = icmp|fcmp|binary instruction ...
5570 // %cond2 = icmp|fcmp|binary instruction ...
5571 // %cond.or = or|and i1 %cond1, cond2
5572 // br i1 %cond.or label %dest1, label %dest2"
5573 BinaryOperator *LogicOp;
5574 BasicBlock *TBB, *FBB;
5575 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5576 continue;
5577
Sanjay Patel42574202015-09-02 19:23:23 +00005578 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5579 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5580 continue;
5581
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005582 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005583 Value *Cond1, *Cond2;
5584 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5585 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005586 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005587 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5588 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005589 Opc = Instruction::Or;
5590 else
5591 continue;
5592
5593 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5594 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5595 continue;
5596
5597 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5598
5599 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005600 auto TmpBB =
5601 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5602 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005603
5604 // Update original basic block by using the first condition directly by the
5605 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005606 Br1->setCondition(Cond1);
5607 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005608
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005609 // Depending on the conditon we have to either replace the true or the false
5610 // successor of the original branch instruction.
5611 if (Opc == Instruction::And)
5612 Br1->setSuccessor(0, TmpBB);
5613 else
5614 Br1->setSuccessor(1, TmpBB);
5615
5616 // Fill in the new basic block.
5617 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005618 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5619 I->removeFromParent();
5620 I->insertBefore(Br2);
5621 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005622
5623 // Update PHI nodes in both successors. The original BB needs to be
5624 // replaced in one succesor's PHI nodes, because the branch comes now from
5625 // the newly generated BB (NewBB). In the other successor we need to add one
5626 // incoming edge to the PHI nodes, because both branch instructions target
5627 // now the same successor. Depending on the original branch condition
5628 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00005629 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005630 // This doesn't change the successor order of the just created branch
5631 // instruction (or any other instruction).
5632 if (Opc == Instruction::Or)
5633 std::swap(TBB, FBB);
5634
5635 // Replace the old BB with the new BB.
5636 for (auto &I : *TBB) {
5637 PHINode *PN = dyn_cast<PHINode>(&I);
5638 if (!PN)
5639 break;
5640 int i;
5641 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5642 PN->setIncomingBlock(i, TmpBB);
5643 }
5644
5645 // Add another incoming edge form the new BB.
5646 for (auto &I : *FBB) {
5647 PHINode *PN = dyn_cast<PHINode>(&I);
5648 if (!PN)
5649 break;
5650 auto *Val = PN->getIncomingValueForBlock(&BB);
5651 PN->addIncoming(Val, TmpBB);
5652 }
5653
5654 // Update the branch weights (from SelectionDAGBuilder::
5655 // FindMergedConditions).
5656 if (Opc == Instruction::Or) {
5657 // Codegen X | Y as:
5658 // BB1:
5659 // jmp_if_X TBB
5660 // jmp TmpBB
5661 // TmpBB:
5662 // jmp_if_Y TBB
5663 // jmp FBB
5664 //
5665
5666 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5667 // The requirement is that
5668 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5669 // = TrueProb for orignal BB.
5670 // Assuming the orignal weights are A and B, one choice is to set BB1's
5671 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5672 // assumes that
5673 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5674 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5675 // TmpBB, but the math is more complicated.
5676 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005677 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005678 uint64_t NewTrueWeight = TrueWeight;
5679 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5680 scaleWeights(NewTrueWeight, NewFalseWeight);
5681 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5682 .createBranchWeights(TrueWeight, FalseWeight));
5683
5684 NewTrueWeight = TrueWeight;
5685 NewFalseWeight = 2 * FalseWeight;
5686 scaleWeights(NewTrueWeight, NewFalseWeight);
5687 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5688 .createBranchWeights(TrueWeight, FalseWeight));
5689 }
5690 } else {
5691 // Codegen X & Y as:
5692 // BB1:
5693 // jmp_if_X TmpBB
5694 // jmp FBB
5695 // TmpBB:
5696 // jmp_if_Y TBB
5697 // jmp FBB
5698 //
5699 // This requires creation of TmpBB after CurBB.
5700
5701 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5702 // The requirement is that
5703 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5704 // = FalseProb for orignal BB.
5705 // Assuming the orignal weights are A and B, one choice is to set BB1's
5706 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5707 // assumes that
5708 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5709 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005710 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005711 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5712 uint64_t NewFalseWeight = FalseWeight;
5713 scaleWeights(NewTrueWeight, NewFalseWeight);
5714 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5715 .createBranchWeights(TrueWeight, FalseWeight));
5716
5717 NewTrueWeight = 2 * TrueWeight;
5718 NewFalseWeight = FalseWeight;
5719 scaleWeights(NewTrueWeight, NewFalseWeight);
5720 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5721 .createBranchWeights(TrueWeight, FalseWeight));
5722 }
5723 }
5724
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005725 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005726 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005727 ModifiedDT = true;
5728
5729 MadeChange = true;
5730
5731 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5732 TmpBB->dump());
5733 }
5734 return MadeChange;
5735}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005736
5737void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005738 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005739 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5740}