blob: cc4af1efba639db0c83af0dddab07854a747c480 [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"
Chandler Carruth62d42152015-01-15 02:16:27 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000024#include "llvm/Analysis/ValueTracking.h"
Petar Jovanovic644b8c12016-04-13 12:25:25 +000025#include "llvm/Analysis/MemoryBuiltins.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000026#include "llvm/CodeGen/Analysis.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000033#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/InlineAsm.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000039#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000040#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000041#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000042#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000043#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000044#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000045#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000046#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000049#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000050#include "llvm/Transforms/Utils/BasicBlockUtils.h"
51#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000052#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000053#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000054#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000055using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000056using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000057
Chandler Carruth1b9dde02014-04-22 02:02:50 +000058#define DEBUG_TYPE "codegenprepare"
59
Cameron Zwarichced753f2011-01-05 17:27:27 +000060STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000061STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
62STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000063STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
64 "sunken Cmps");
65STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
66 "of sunken Casts");
67STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
68 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000069STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
70STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000071STATISTIC(NumAndsAdded,
72 "Number of and mask instructions added to form ext loads");
73STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000074STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000075STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000076STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000077STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000078STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000079
Cameron Zwarich338d3622011-03-11 21:52:04 +000080static cl::opt<bool> DisableBranchOpts(
81 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
82 cl::desc("Disable branch optimizations in CodeGenPrepare"));
83
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000084static cl::opt<bool>
85 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
86 cl::desc("Disable GC optimizations in CodeGenPrepare"));
87
Benjamin Kramer3d38c172012-05-06 14:25:16 +000088static cl::opt<bool> DisableSelectToBranch(
89 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
90 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000091
Hal Finkelc3998302014-04-12 00:59:48 +000092static cl::opt<bool> AddrSinkUsingGEPs(
93 "addr-sink-using-gep", cl::Hidden, cl::init(false),
94 cl::desc("Address sinking in CGP using GEPs."));
95
Tim Northovercea0abb2014-03-29 08:22:29 +000096static cl::opt<bool> EnableAndCmpSinking(
97 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
98 cl::desc("Enable sinkinig and/cmp into branches."));
99
Quentin Colombetc32615d2014-10-31 17:52:53 +0000100static cl::opt<bool> DisableStoreExtract(
101 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
102 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
103
104static cl::opt<bool> StressStoreExtract(
105 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
106 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
107
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000108static cl::opt<bool> DisableExtLdPromotion(
109 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
110 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
111 "CodeGenPrepare"));
112
113static cl::opt<bool> StressExtLdPromotion(
114 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
115 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
116 "optimization in CodeGenPrepare"));
117
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000118static cl::opt<bool> DisablePreheaderProtect(
119 "disable-preheader-prot", cl::Hidden, cl::init(false),
120 cl::desc("Disable protection against removing loop preheaders"));
121
Eric Christopherc1ea1492008-09-24 05:32:41 +0000122namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000123typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000124typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000125typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000126class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000127
Chris Lattner2dd09db2009-09-02 06:11:42 +0000128 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000129 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000130 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000131 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000132 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000133 const LoopInfo *LI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000134
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000135 /// As we scan instructions optimizing them, this is the next instruction
136 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000137 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000138
Evan Cheng0663f232011-03-21 01:19:09 +0000139 /// Keeps track of non-local addresses that have been sunk into a block.
140 /// This allows us to avoid inserting duplicate code for blocks with
141 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000142 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000143
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000144 /// Keeps track of all instructions inserted for the current function.
145 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000146 /// Keeps track of the type of the related instruction before their
147 /// promotion for the current function.
148 InstrToOrigTy PromotedInsts;
149
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000150 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000151 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000152
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000153 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000154 bool OptSize;
155
Mehdi Amini4fe37982015-07-07 18:45:17 +0000156 /// DataLayout for the Function being processed.
157 const DataLayout *DL;
158
Chris Lattnerf2836d12007-03-31 04:06:36 +0000159 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000160 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000161 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000162 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000163 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
164 }
Craig Topper4584cd52014-03-07 09:26:03 +0000165 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000166
Mehdi Amini117296c2016-10-01 02:56:57 +0000167 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000168
Craig Topper4584cd52014-03-07 09:26:03 +0000169 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000170 // FIXME: When we can selectively preserve passes, preserve the domtree.
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000171 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000172 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000173 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000174 }
175
Chris Lattnerf2836d12007-03-31 04:06:36 +0000176 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000177 bool eliminateFallThrough(Function &F);
178 bool eliminateMostlyEmptyBlocks(Function &F);
179 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
180 void eliminateMostlyEmptyBlock(BasicBlock *BB);
181 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
182 bool optimizeInst(Instruction *I, bool& ModifiedDT);
183 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000184 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000185 bool optimizeInlineAsmInst(CallInst *CS);
186 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
187 bool moveExtToFormExtLoad(Instruction *&I);
188 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000189 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000190 bool optimizeSelectInst(SelectInst *SI);
191 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000192 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000193 bool optimizeExtractElementInst(Instruction *Inst);
194 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
195 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000196 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000197 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000198 Instruction *&Inst,
199 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000200 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000201 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000202 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000203 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000204 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000205}
Devang Patel09f162c2007-05-01 21:15:47 +0000206
Devang Patel8c78a0b2007-05-03 01:11:54 +0000207char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000208INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
209 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000210
Bill Wendling7a639ea2013-06-19 21:07:11 +0000211FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
212 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000213}
214
Chris Lattnerf2836d12007-03-31 04:06:36 +0000215bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000216 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000217 return false;
218
Mehdi Amini4fe37982015-07-07 18:45:17 +0000219 DL = &F.getParent()->getDataLayout();
220
Chris Lattnerf2836d12007-03-31 04:06:36 +0000221 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000222 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000223 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000224 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000225
Devang Patel8f606d72011-03-24 15:35:25 +0000226 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000227 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000228 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000229 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000230 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000231 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000232 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000233
Preston Gurdcdf540d2012-09-04 18:22:17 +0000234 /// This optimization identifies DIV instructions that can be
235 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000236 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000237 const DenseMap<unsigned int, unsigned int> &BypassWidths =
238 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000239 BasicBlock* BB = &*F.begin();
240 while (BB != nullptr) {
241 // bypassSlowDivision may create new BBs, but we don't want to reapply the
242 // optimization to those blocks.
243 BasicBlock* Next = BB->getNextNode();
244 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
245 BB = Next;
246 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000247 }
248
249 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000250 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000251 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000252
Devang Patel53771ba2011-08-18 00:50:51 +0000253 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000254 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000255 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000256 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000257
Tim Northovercea0abb2014-03-29 08:22:29 +0000258 // If there is a mask, compare against zero, and branch that can be combined
259 // into a single target instruction, push the mask and compare into branch
260 // users. Do this before OptimizeBlock -> OptimizeInst ->
261 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000262 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000263 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000264 EverMadeChange |= splitBranchCondition(F);
265 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000266
Chris Lattnerc3748562007-04-02 01:35:34 +0000267 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000268 while (MadeChange) {
269 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000270 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000271 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000272 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000273 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000274
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000275 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000276 if (ModifiedDTOnIteration)
277 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000278 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000279 EverMadeChange |= MadeChange;
280 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000281
282 SunkAddrs.clear();
283
Cameron Zwarich338d3622011-03-11 21:52:04 +0000284 if (!DisableBranchOpts) {
285 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000286 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000287 for (BasicBlock &BB : F) {
288 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
289 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000290 if (!MadeChange) continue;
291
292 for (SmallVectorImpl<BasicBlock*>::iterator
293 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
294 if (pred_begin(*II) == pred_end(*II))
295 WorkList.insert(*II);
296 }
297
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000298 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000299 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000300 while (!WorkList.empty()) {
301 BasicBlock *BB = *WorkList.begin();
302 WorkList.erase(BB);
303 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
304
305 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000306
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000307 for (SmallVectorImpl<BasicBlock*>::iterator
308 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
309 if (pred_begin(*II) == pred_end(*II))
310 WorkList.insert(*II);
311 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000312
Nadav Rotem70409992012-08-14 05:19:07 +0000313 // Merge pairs of basic blocks with unconditional branches, connected by
314 // a single edge.
315 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000316 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000317
Cameron Zwarich338d3622011-03-11 21:52:04 +0000318 EverMadeChange |= MadeChange;
319 }
320
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000321 if (!DisableGCOpts) {
322 SmallVector<Instruction *, 2> Statepoints;
323 for (BasicBlock &BB : F)
324 for (Instruction &I : BB)
325 if (isStatepoint(I))
326 Statepoints.push_back(&I);
327 for (auto &I : Statepoints)
328 EverMadeChange |= simplifyOffsetableRelocate(*I);
329 }
330
Chris Lattnerf2836d12007-03-31 04:06:36 +0000331 return EverMadeChange;
332}
333
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000334/// Merge basic blocks which are connected by a single edge, where one of the
335/// basic blocks has a single successor pointing to the other basic block,
336/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000337bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000338 bool Changed = false;
339 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000340 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000341 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000342 // If the destination block has a single pred, then this is a trivial
343 // edge, just collapse it.
344 BasicBlock *SinglePred = BB->getSinglePredecessor();
345
Evan Cheng64a223a2012-09-28 23:58:57 +0000346 // Don't merge if BB's address is taken.
347 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000348
349 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
350 if (Term && !Term->isConditional()) {
351 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000352 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000353 // Remember if SinglePred was the entry block of the function.
354 // If so, we will need to move BB back to the entry position.
355 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000356 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000357
358 if (isEntry && BB != &BB->getParent()->getEntryBlock())
359 BB->moveBefore(&BB->getParent()->getEntryBlock());
360
361 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000362 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000363 }
364 }
365 return Changed;
366}
367
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000368/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
369/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
370/// edges in ways that are non-optimal for isel. Start by eliminating these
371/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000372bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000373 SmallPtrSet<BasicBlock *, 16> Preheaders;
374 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
375 while (!LoopList.empty()) {
376 Loop *L = LoopList.pop_back_val();
377 LoopList.insert(LoopList.end(), L->begin(), L->end());
378 if (BasicBlock *Preheader = L->getLoopPreheader())
379 Preheaders.insert(Preheader);
380 }
381
Chris Lattnerc3748562007-04-02 01:35:34 +0000382 bool MadeChange = false;
383 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000384 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000385 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000386
387 // If this block doesn't end with an uncond branch, ignore it.
388 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
389 if (!BI || !BI->isUnconditional())
390 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000391
Dale Johannesen4026b042009-03-27 01:13:37 +0000392 // If the instruction before the branch (skipping debug info) isn't a phi
393 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000394 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000395 if (BBI != BB->begin()) {
396 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000397 while (isa<DbgInfoIntrinsic>(BBI)) {
398 if (BBI == BB->begin())
399 break;
400 --BBI;
401 }
402 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
403 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000404 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000405
Chris Lattnerc3748562007-04-02 01:35:34 +0000406 // Do not break infinite loops.
407 BasicBlock *DestBB = BI->getSuccessor(0);
408 if (DestBB == BB)
409 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000410
Sanjay Patelfc580a62015-09-21 23:03:16 +0000411 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000412 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000413
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000414 // Do not delete loop preheaders if doing so would create a critical edge.
415 // Loop preheaders can be good locations to spill registers. If the
416 // preheader is deleted and we create a critical edge, registers may be
417 // spilled in the loop body instead.
418 if (!DisablePreheaderProtect && Preheaders.count(BB) &&
419 !(BB->getSinglePredecessor() && BB->getSinglePredecessor()->getSingleSuccessor()))
420 continue;
421
Sanjay Patelfc580a62015-09-21 23:03:16 +0000422 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000423 MadeChange = true;
424 }
425 return MadeChange;
426}
427
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000428/// Return true if we can merge BB into DestBB if there is a single
429/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000430/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000431bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000432 const BasicBlock *DestBB) const {
433 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
434 // the successor. If there are more complex condition (e.g. preheaders),
435 // don't mess around with them.
436 BasicBlock::const_iterator BBI = BB->begin();
437 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000438 for (const User *U : PN->users()) {
439 const Instruction *UI = cast<Instruction>(U);
440 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000441 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442 // If User is inside DestBB block and it is a PHINode then check
443 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000444 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000445 if (UI->getParent() == DestBB) {
446 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000447 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
448 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
449 if (Insn && Insn->getParent() == BB &&
450 Insn->getParent() != UPN->getIncomingBlock(I))
451 return false;
452 }
453 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000454 }
455 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000456
Chris Lattnerc3748562007-04-02 01:35:34 +0000457 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
458 // and DestBB may have conflicting incoming values for the block. If so, we
459 // can't merge the block.
460 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
461 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000462
Chris Lattnerc3748562007-04-02 01:35:34 +0000463 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000464 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000465 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
466 // It is faster to get preds from a PHI than with pred_iterator.
467 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
468 BBPreds.insert(BBPN->getIncomingBlock(i));
469 } else {
470 BBPreds.insert(pred_begin(BB), pred_end(BB));
471 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000472
Chris Lattnerc3748562007-04-02 01:35:34 +0000473 // Walk the preds of DestBB.
474 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
475 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
476 if (BBPreds.count(Pred)) { // Common predecessor?
477 BBI = DestBB->begin();
478 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
479 const Value *V1 = PN->getIncomingValueForBlock(Pred);
480 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000481
Chris Lattnerc3748562007-04-02 01:35:34 +0000482 // If V2 is a phi node in BB, look up what the mapped value will be.
483 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
484 if (V2PN->getParent() == BB)
485 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000486
Chris Lattnerc3748562007-04-02 01:35:34 +0000487 // If there is a conflict, bail out.
488 if (V1 != V2) return false;
489 }
490 }
491 }
492
493 return true;
494}
495
496
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000497/// Eliminate a basic block that has only phi's and an unconditional branch in
498/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000499void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000500 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
501 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000502
David Greene74e2d492010-01-05 01:27:11 +0000503 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000504
Chris Lattnerc3748562007-04-02 01:35:34 +0000505 // If the destination block has a single pred, then this is a trivial edge,
506 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000507 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000508 if (SinglePred != DestBB) {
509 // Remember if SinglePred was the entry block of the function. If so, we
510 // will need to move BB back to the entry position.
511 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000512 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000513
Chris Lattner8a172da2008-11-28 19:54:49 +0000514 if (isEntry && BB != &BB->getParent()->getEntryBlock())
515 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000516
David Greene74e2d492010-01-05 01:27:11 +0000517 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000518 return;
519 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000520 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000521
Chris Lattnerc3748562007-04-02 01:35:34 +0000522 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
523 // to handle the new incoming edges it is about to have.
524 PHINode *PN;
525 for (BasicBlock::iterator BBI = DestBB->begin();
526 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
527 // Remove the incoming value for BB, and remember it.
528 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000529
Chris Lattnerc3748562007-04-02 01:35:34 +0000530 // Two options: either the InVal is a phi node defined in BB or it is some
531 // value that dominates BB.
532 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
533 if (InValPhi && InValPhi->getParent() == BB) {
534 // Add all of the input values of the input PHI as inputs of this phi.
535 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
536 PN->addIncoming(InValPhi->getIncomingValue(i),
537 InValPhi->getIncomingBlock(i));
538 } else {
539 // Otherwise, add one instance of the dominating value for each edge that
540 // we will be adding.
541 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
542 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
543 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
544 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000545 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
546 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000547 }
548 }
549 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000550
Chris Lattnerc3748562007-04-02 01:35:34 +0000551 // The PHIs are now updated, change everything that refers to BB to use
552 // DestBB and remove BB.
553 BB->replaceAllUsesWith(DestBB);
554 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000555 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000556
David Greene74e2d492010-01-05 01:27:11 +0000557 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000558}
559
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000560// Computes a map of base pointer relocation instructions to corresponding
561// derived pointer relocation instructions given a vector of all relocate calls
562static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000563 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
564 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
565 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000566 // Collect information in two maps: one primarily for locating the base object
567 // while filling the second map; the second map is the final structure holding
568 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000569 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
570 for (auto *ThisRelocate : AllRelocateCalls) {
571 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
572 ThisRelocate->getDerivedPtrIndex());
573 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000574 }
575 for (auto &Item : RelocateIdxMap) {
576 std::pair<unsigned, unsigned> Key = Item.first;
577 if (Key.first == Key.second)
578 // Base relocation: nothing to insert
579 continue;
580
Manuel Jacob83eefa62016-01-05 04:03:00 +0000581 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000582 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000583
584 // We're iterating over RelocateIdxMap so we cannot modify it.
585 auto MaybeBase = RelocateIdxMap.find(BaseKey);
586 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000587 // TODO: We might want to insert a new base object relocate and gep off
588 // that, if there are enough derived object relocates.
589 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000590
591 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000592 }
593}
594
595// Accepts a GEP and extracts the operands into a vector provided they're all
596// small integer constants
597static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
598 SmallVectorImpl<Value *> &OffsetV) {
599 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
600 // Only accept small constant integer operands
601 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
602 if (!Op || Op->getZExtValue() > 20)
603 return false;
604 }
605
606 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
607 OffsetV.push_back(GEP->getOperand(i));
608 return true;
609}
610
611// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
612// replace, computes a replacement, and affects it.
613static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000614simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
615 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000616 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000617 for (GCRelocateInst *ToReplace : Targets) {
618 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000619 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000620 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000621 // A duplicate relocate call. TODO: coalesce duplicates.
622 continue;
623 }
624
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000625 if (RelocatedBase->getParent() != ToReplace->getParent()) {
626 // Base and derived relocates are in different basic blocks.
627 // In this case transform is only valid when base dominates derived
628 // relocate. However it would be too expensive to check dominance
629 // for each such relocate, so we skip the whole transformation.
630 continue;
631 }
632
Manuel Jacob83eefa62016-01-05 04:03:00 +0000633 Value *Base = ToReplace->getBasePtr();
634 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000635 if (!Derived || Derived->getPointerOperand() != Base)
636 continue;
637
638 SmallVector<Value *, 2> OffsetV;
639 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
640 continue;
641
642 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000643 assert(RelocatedBase->getNextNode() &&
644 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000645
646 // Insert after RelocatedBase
647 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000648 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000649
650 // If gc_relocate does not match the actual type, cast it to the right type.
651 // In theory, there must be a bitcast after gc_relocate if the type does not
652 // match, and we should reuse it to get the derived pointer. But it could be
653 // cases like this:
654 // bb1:
655 // ...
656 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
657 // br label %merge
658 //
659 // bb2:
660 // ...
661 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
662 // br label %merge
663 //
664 // merge:
665 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
666 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
667 //
668 // In this case, we can not find the bitcast any more. So we insert a new bitcast
669 // no matter there is already one or not. In this way, we can handle all cases, and
670 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000671 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000672 if (RelocatedBase->getType() != Base->getType()) {
673 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000674 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000675 }
David Blaikie68d535c2015-03-24 22:38:16 +0000676 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000677 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000678 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000679 // If the newly generated derived pointer's type does not match the original derived
680 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000681 Value *ActualReplacement = Replacement;
682 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000683 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000684 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000685 }
686 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000687 ToReplace->eraseFromParent();
688
689 MadeChange = true;
690 }
691 return MadeChange;
692}
693
694// Turns this:
695//
696// %base = ...
697// %ptr = gep %base + 15
698// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
699// %base' = relocate(%tok, i32 4, i32 4)
700// %ptr' = relocate(%tok, i32 4, i32 5)
701// %val = load %ptr'
702//
703// into this:
704//
705// %base = ...
706// %ptr = gep %base + 15
707// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
708// %base' = gc.relocate(%tok, i32 4, i32 4)
709// %ptr' = gep %base' + 15
710// %val = load %ptr'
711bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
712 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000713 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000714
715 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000716 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000717 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000718 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000719
720 // We need atleast one base pointer relocation + one derived pointer
721 // relocation to mangle
722 if (AllRelocateCalls.size() < 2)
723 return false;
724
725 // RelocateInstMap is a mapping from the base relocate instruction to the
726 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000727 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000728 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
729 if (RelocateInstMap.empty())
730 return false;
731
732 for (auto &Item : RelocateInstMap)
733 // Item.first is the RelocatedBase to offset against
734 // Item.second is the vector of Targets to replace
735 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
736 return MadeChange;
737}
738
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000739/// SinkCast - Sink the specified cast instruction into its user blocks
740static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000741 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000742
Chris Lattnerf2836d12007-03-31 04:06:36 +0000743 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000744 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000745
Chris Lattnerf2836d12007-03-31 04:06:36 +0000746 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000747 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000748 UI != E; ) {
749 Use &TheUse = UI.getUse();
750 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000751
Chris Lattnerf2836d12007-03-31 04:06:36 +0000752 // Figure out which BB this cast is used in. For PHI's this is the
753 // appropriate predecessor block.
754 BasicBlock *UserBB = User->getParent();
755 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000756 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000757 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000758
Chris Lattnerf2836d12007-03-31 04:06:36 +0000759 // Preincrement use iterator so we don't invalidate it.
760 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000761
David Majnemer0c80e2e2016-04-27 19:36:38 +0000762 // The first insertion point of a block containing an EH pad is after the
763 // pad. If the pad is the user, we cannot sink the cast past the pad.
764 if (User->isEHPad())
765 continue;
766
Andrew Kaylord0430e82015-11-23 19:16:15 +0000767 // If the block selected to receive the cast is an EH pad that does not
768 // allow non-PHI instructions before the terminator, we can't sink the
769 // cast.
770 if (UserBB->getTerminator()->isEHPad())
771 continue;
772
Chris Lattnerf2836d12007-03-31 04:06:36 +0000773 // If this user is in the same block as the cast, don't change the cast.
774 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000775
Chris Lattnerf2836d12007-03-31 04:06:36 +0000776 // If we have already inserted a cast into this block, use it.
777 CastInst *&InsertedCast = InsertedCasts[UserBB];
778
779 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000780 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000781 assert(InsertPt != UserBB->end());
782 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
783 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000784 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000785
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000786 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000787 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000788 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000789 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000790 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000791
Chris Lattnerf2836d12007-03-31 04:06:36 +0000792 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000793 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000794 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000795 MadeChange = true;
796 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000797
Chris Lattnerf2836d12007-03-31 04:06:36 +0000798 return MadeChange;
799}
800
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000801/// If the specified cast instruction is a noop copy (e.g. it's casting from
802/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
803/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000804///
805/// Return true if any changes are made.
806///
Mehdi Amini44ede332015-07-09 02:09:04 +0000807static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
808 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000809 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000810 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
811 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000812
813 // This is an fp<->int conversion?
814 if (SrcVT.isInteger() != DstVT.isInteger())
815 return false;
816
817 // If this is an extension, it will be a zero or sign extension, which
818 // isn't a noop.
819 if (SrcVT.bitsLT(DstVT)) return false;
820
821 // If these values will be promoted, find out what they will be promoted
822 // to. This helps us consider truncates on PPC as noop copies when they
823 // are.
824 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
825 TargetLowering::TypePromoteInteger)
826 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
827 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
828 TargetLowering::TypePromoteInteger)
829 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
830
831 // If, after promotion, these are the same types, this is a noop copy.
832 if (SrcVT != DstVT)
833 return false;
834
835 return SinkCast(CI);
836}
837
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000838/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
839/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000840///
841/// Return true if any changes were made.
842static bool CombineUAddWithOverflow(CmpInst *CI) {
843 Value *A, *B;
844 Instruction *AddI;
845 if (!match(CI,
846 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
847 return false;
848
849 Type *Ty = AddI->getType();
850 if (!isa<IntegerType>(Ty))
851 return false;
852
853 // We don't want to move around uses of condition values this late, so we we
854 // check if it is legal to create the call to the intrinsic in the basic
855 // block containing the icmp:
856
857 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
858 return false;
859
860#ifndef NDEBUG
861 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
862 // for now:
863 if (AddI->hasOneUse())
864 assert(*AddI->user_begin() == CI && "expected!");
865#endif
866
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000867 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000868 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
869
870 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
871
872 auto *UAddWithOverflow =
873 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
874 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
875 auto *Overflow =
876 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
877
878 CI->replaceAllUsesWith(Overflow);
879 AddI->replaceAllUsesWith(UAdd);
880 CI->eraseFromParent();
881 AddI->eraseFromParent();
882 return true;
883}
884
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000885/// Sink the given CmpInst into user blocks to reduce the number of virtual
886/// registers that must be created and coalesced. This is a clear win except on
887/// targets with multiple condition code registers (PowerPC), where it might
888/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000889///
890/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000891static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000892 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000893
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000894 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000895 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000896 return false;
897
898 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000899 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000900
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000901 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000902 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000903 UI != E; ) {
904 Use &TheUse = UI.getUse();
905 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000906
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000907 // Preincrement use iterator so we don't invalidate it.
908 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000909
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000910 // Don't bother for PHI nodes.
911 if (isa<PHINode>(User))
912 continue;
913
914 // Figure out which BB this cmp is used in.
915 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000916
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000917 // If this user is in the same block as the cmp, don't change the cmp.
918 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000919
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000920 // If we have already inserted a cmp into this block, use it.
921 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
922
923 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000924 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000925 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000926 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000927 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
928 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +0000929 // Propagate the debug info.
930 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000931 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000932
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000933 // Replace a use of the cmp with a use of the new cmp.
934 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000935 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000936 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000937 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000938
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000939 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000940 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000941 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000942 MadeChange = true;
943 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000944
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000945 return MadeChange;
946}
947
Peter Zotovf87e5502016-04-03 17:11:53 +0000948static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +0000949 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000950 return true;
951
952 if (CombineUAddWithOverflow(CI))
953 return true;
954
955 return false;
956}
957
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000958/// Check if the candidates could be combined with a shift instruction, which
959/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000960/// 1. Truncate instruction
961/// 2. And instruction and the imm is a mask of the low bits:
962/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000963static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000964 if (!isa<TruncInst>(User)) {
965 if (User->getOpcode() != Instruction::And ||
966 !isa<ConstantInt>(User->getOperand(1)))
967 return false;
968
Quentin Colombetd4f44692014-04-22 01:20:34 +0000969 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000970
Quentin Colombetd4f44692014-04-22 01:20:34 +0000971 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000972 return false;
973 }
974 return true;
975}
976
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000977/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000978static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000979SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
980 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000981 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000982 BasicBlock *UserBB = User->getParent();
983 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
984 TruncInst *TruncI = dyn_cast<TruncInst>(User);
985 bool MadeChange = false;
986
987 for (Value::user_iterator TruncUI = TruncI->user_begin(),
988 TruncE = TruncI->user_end();
989 TruncUI != TruncE;) {
990
991 Use &TruncTheUse = TruncUI.getUse();
992 Instruction *TruncUser = cast<Instruction>(*TruncUI);
993 // Preincrement use iterator so we don't invalidate it.
994
995 ++TruncUI;
996
997 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
998 if (!ISDOpcode)
999 continue;
1000
Tim Northovere2239ff2014-07-29 10:20:22 +00001001 // If the use is actually a legal node, there will not be an
1002 // implicit truncate.
1003 // FIXME: always querying the result type is just an
1004 // approximation; some nodes' legality is determined by the
1005 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001006 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001007 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001008 continue;
1009
1010 // Don't bother for PHI nodes.
1011 if (isa<PHINode>(TruncUser))
1012 continue;
1013
1014 BasicBlock *TruncUserBB = TruncUser->getParent();
1015
1016 if (UserBB == TruncUserBB)
1017 continue;
1018
1019 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1020 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1021
1022 if (!InsertedShift && !InsertedTrunc) {
1023 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001024 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001025 // Sink the shift
1026 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001027 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1028 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001029 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001030 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1031 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001032
1033 // Sink the trunc
1034 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1035 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001036 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001037
1038 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001039 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001040
1041 MadeChange = true;
1042
1043 TruncTheUse = InsertedTrunc;
1044 }
1045 }
1046 return MadeChange;
1047}
1048
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001049/// Sink the shift *right* instruction into user blocks if the uses could
1050/// potentially be combined with this shift instruction and generate BitExtract
1051/// instruction. It will only be applied if the architecture supports BitExtract
1052/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001053/// BB1:
1054/// %x.extract.shift = lshr i64 %arg1, 32
1055/// BB2:
1056/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1057/// ==>
1058///
1059/// BB2:
1060/// %x.extract.shift.1 = lshr i64 %arg1, 32
1061/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1062///
1063/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1064/// instruction.
1065/// Return true if any changes are made.
1066static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001067 const TargetLowering &TLI,
1068 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001069 BasicBlock *DefBB = ShiftI->getParent();
1070
1071 /// Only insert instructions in each block once.
1072 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1073
Mehdi Amini44ede332015-07-09 02:09:04 +00001074 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001075
1076 bool MadeChange = false;
1077 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1078 UI != E;) {
1079 Use &TheUse = UI.getUse();
1080 Instruction *User = cast<Instruction>(*UI);
1081 // Preincrement use iterator so we don't invalidate it.
1082 ++UI;
1083
1084 // Don't bother for PHI nodes.
1085 if (isa<PHINode>(User))
1086 continue;
1087
1088 if (!isExtractBitsCandidateUse(User))
1089 continue;
1090
1091 BasicBlock *UserBB = User->getParent();
1092
1093 if (UserBB == DefBB) {
1094 // If the shift and truncate instruction are in the same BB. The use of
1095 // the truncate(TruncUse) may still introduce another truncate if not
1096 // legal. In this case, we would like to sink both shift and truncate
1097 // instruction to the BB of TruncUse.
1098 // for example:
1099 // BB1:
1100 // i64 shift.result = lshr i64 opnd, imm
1101 // trunc.result = trunc shift.result to i16
1102 //
1103 // BB2:
1104 // ----> We will have an implicit truncate here if the architecture does
1105 // not have i16 compare.
1106 // cmp i16 trunc.result, opnd2
1107 //
1108 if (isa<TruncInst>(User) && shiftIsLegal
1109 // If the type of the truncate is legal, no trucate will be
1110 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001111 &&
1112 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001113 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001114 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001115
1116 continue;
1117 }
1118 // If we have already inserted a shift into this block, use it.
1119 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1120
1121 if (!InsertedShift) {
1122 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001123 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001124
1125 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001126 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1127 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001128 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001129 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1130 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001131
1132 MadeChange = true;
1133 }
1134
1135 // Replace a use of the shift with a use of the new shift.
1136 TheUse = InsertedShift;
1137 }
1138
1139 // If we removed all uses, nuke the shift.
1140 if (ShiftI->use_empty())
1141 ShiftI->eraseFromParent();
1142
1143 return MadeChange;
1144}
1145
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001146// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001147// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1148// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001149// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001150// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001151//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001152// %1 = bitcast i8* %addr to i32*
1153// %2 = extractelement <16 x i1> %mask, i32 0
1154// %3 = icmp eq i1 %2, true
1155// br i1 %3, label %cond.load, label %else
1156//
1157//cond.load: ; preds = %0
1158// %4 = getelementptr i32* %1, i32 0
1159// %5 = load i32* %4
1160// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1161// br label %else
1162//
1163//else: ; preds = %0, %cond.load
1164// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1165// %7 = extractelement <16 x i1> %mask, i32 1
1166// %8 = icmp eq i1 %7, true
1167// br i1 %8, label %cond.load1, label %else2
1168//
1169//cond.load1: ; preds = %else
1170// %9 = getelementptr i32* %1, i32 1
1171// %10 = load i32* %9
1172// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1173// br label %else2
1174//
1175//else2: ; preds = %else, %cond.load1
1176// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1177// %12 = extractelement <16 x i1> %mask, i32 2
1178// %13 = icmp eq i1 %12, true
1179// br i1 %13, label %cond.load4, label %else5
1180//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001181static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001182 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001183 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001184 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001185 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001186
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001187 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1188 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001189 assert(VecType && "Unexpected return type of masked load intrinsic");
1190
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001191 Type *EltTy = CI->getType()->getVectorElementType();
1192
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001193 IRBuilder<> Builder(CI->getContext());
1194 Instruction *InsertPt = CI;
1195 BasicBlock *IfBlock = CI->getParent();
1196 BasicBlock *CondBlock = nullptr;
1197 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001198
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001199 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001200 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1201
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001202 // Short-cut if the mask is all-true.
1203 bool IsAllOnesMask = isa<Constant>(Mask) &&
1204 cast<Constant>(Mask)->isAllOnesValue();
1205
1206 if (IsAllOnesMask) {
1207 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1208 CI->replaceAllUsesWith(NewI);
1209 CI->eraseFromParent();
1210 return;
1211 }
1212
1213 // Adjust alignment for the scalar instruction.
1214 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001215 // Bitcast %addr fron i8* to EltTy*
1216 Type *NewPtrType =
1217 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1218 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001219 unsigned VectorWidth = VecType->getNumElements();
1220
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001221 Value *UndefVal = UndefValue::get(VecType);
1222
1223 // The result vector
1224 Value *VResult = UndefVal;
1225
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001226 if (isa<ConstantVector>(Mask)) {
1227 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1228 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1229 continue;
1230 Value *Gep =
1231 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1232 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1233 VResult = Builder.CreateInsertElement(VResult, Load,
1234 Builder.getInt32(Idx));
1235 }
1236 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1237 CI->replaceAllUsesWith(NewI);
1238 CI->eraseFromParent();
1239 return;
1240 }
1241
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001242 PHINode *Phi = nullptr;
1243 Value *PrevPhi = UndefVal;
1244
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001245 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1246
1247 // Fill the "else" block, created in the previous iteration
1248 //
1249 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1250 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1251 // %to_load = icmp eq i1 %mask_1, true
1252 // br i1 %to_load, label %cond.load, label %else
1253 //
1254 if (Idx > 0) {
1255 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1256 Phi->addIncoming(VResult, CondBlock);
1257 Phi->addIncoming(PrevPhi, PrevIfBlock);
1258 PrevPhi = Phi;
1259 VResult = Phi;
1260 }
1261
1262 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1263 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1264 ConstantInt::get(Predicate->getType(), 1));
1265
1266 // Create "cond" block
1267 //
1268 // %EltAddr = getelementptr i32* %1, i32 0
1269 // %Elt = load i32* %EltAddr
1270 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1271 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001272 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001273 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001274
1275 Value *Gep =
1276 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001277 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001278 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1279
1280 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001281 BasicBlock *NewIfBlock =
1282 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001283 Builder.SetInsertPoint(InsertPt);
1284 Instruction *OldBr = IfBlock->getTerminator();
1285 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1286 OldBr->eraseFromParent();
1287 PrevIfBlock = IfBlock;
1288 IfBlock = NewIfBlock;
1289 }
1290
1291 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1292 Phi->addIncoming(VResult, CondBlock);
1293 Phi->addIncoming(PrevPhi, PrevIfBlock);
1294 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1295 CI->replaceAllUsesWith(NewI);
1296 CI->eraseFromParent();
1297}
1298
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001299// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001300// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1301// <16 x i1> %mask)
1302// to a chain of basic blocks, that stores element one-by-one if
1303// the appropriate mask bit is set
1304//
1305// %1 = bitcast i8* %addr to i32*
1306// %2 = extractelement <16 x i1> %mask, i32 0
1307// %3 = icmp eq i1 %2, true
1308// br i1 %3, label %cond.store, label %else
1309//
1310// cond.store: ; preds = %0
1311// %4 = extractelement <16 x i32> %val, i32 0
1312// %5 = getelementptr i32* %1, i32 0
1313// store i32 %4, i32* %5
1314// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001315//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001316// else: ; preds = %0, %cond.store
1317// %6 = extractelement <16 x i1> %mask, i32 1
1318// %7 = icmp eq i1 %6, true
1319// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001320//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001321// cond.store1: ; preds = %else
1322// %8 = extractelement <16 x i32> %val, i32 1
1323// %9 = getelementptr i32* %1, i32 1
1324// store i32 %8, i32* %9
1325// br label %else2
1326// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001327static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001328 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001329 Value *Ptr = CI->getArgOperand(1);
1330 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001331 Value *Mask = CI->getArgOperand(3);
1332
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001333 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001334 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001335 assert(VecType && "Unexpected data type in masked store intrinsic");
1336
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001337 Type *EltTy = VecType->getElementType();
1338
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001339 IRBuilder<> Builder(CI->getContext());
1340 Instruction *InsertPt = CI;
1341 BasicBlock *IfBlock = CI->getParent();
1342 Builder.SetInsertPoint(InsertPt);
1343 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1344
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001345 // Short-cut if the mask is all-true.
1346 bool IsAllOnesMask = isa<Constant>(Mask) &&
1347 cast<Constant>(Mask)->isAllOnesValue();
1348
1349 if (IsAllOnesMask) {
1350 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1351 CI->eraseFromParent();
1352 return;
1353 }
1354
1355 // Adjust alignment for the scalar instruction.
1356 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001357 // Bitcast %addr fron i8* to EltTy*
1358 Type *NewPtrType =
1359 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1360 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001361 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001362
1363 if (isa<ConstantVector>(Mask)) {
1364 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1365 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1366 continue;
1367 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1368 Value *Gep =
1369 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1370 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1371 }
1372 CI->eraseFromParent();
1373 return;
1374 }
1375
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001376 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1377
1378 // Fill the "else" block, created in the previous iteration
1379 //
1380 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1381 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001382 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001383 //
1384 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1385 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1386 ConstantInt::get(Predicate->getType(), 1));
1387
1388 // Create "cond" block
1389 //
1390 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1391 // %EltAddr = getelementptr i32* %1, i32 0
1392 // %store i32 %OneElt, i32* %EltAddr
1393 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001394 BasicBlock *CondBlock =
1395 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001396 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001397
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001398 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001399 Value *Gep =
1400 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001401 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001402
1403 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001404 BasicBlock *NewIfBlock =
1405 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001406 Builder.SetInsertPoint(InsertPt);
1407 Instruction *OldBr = IfBlock->getTerminator();
1408 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1409 OldBr->eraseFromParent();
1410 IfBlock = NewIfBlock;
1411 }
1412 CI->eraseFromParent();
1413}
1414
Elena Demikhovsky09285852015-10-25 15:37:55 +00001415// Translate a masked gather intrinsic like
1416// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1417// <16 x i1> %Mask, <16 x i32> %Src)
1418// to a chain of basic blocks, with loading element one-by-one if
1419// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001420//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001421// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1422// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1423// % ToLoad0 = icmp eq i1 % Mask0, true
1424// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001425//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001426// cond.load:
1427// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1428// % Load0 = load i32, i32* % Ptr0, align 4
1429// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1430// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001431//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001432// else:
1433// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1434// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1435// % ToLoad1 = icmp eq i1 % Mask1, true
1436// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001437//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001438// cond.load1:
1439// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1440// % Load1 = load i32, i32* % Ptr1, align 4
1441// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1442// br label %else2
1443// . . .
1444// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1445// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001446static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001447 Value *Ptrs = CI->getArgOperand(0);
1448 Value *Alignment = CI->getArgOperand(1);
1449 Value *Mask = CI->getArgOperand(2);
1450 Value *Src0 = CI->getArgOperand(3);
1451
1452 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1453
1454 assert(VecType && "Unexpected return type of masked load intrinsic");
1455
1456 IRBuilder<> Builder(CI->getContext());
1457 Instruction *InsertPt = CI;
1458 BasicBlock *IfBlock = CI->getParent();
1459 BasicBlock *CondBlock = nullptr;
1460 BasicBlock *PrevIfBlock = CI->getParent();
1461 Builder.SetInsertPoint(InsertPt);
1462 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1463
1464 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1465
1466 Value *UndefVal = UndefValue::get(VecType);
1467
1468 // The result vector
1469 Value *VResult = UndefVal;
1470 unsigned VectorWidth = VecType->getNumElements();
1471
1472 // Shorten the way if the mask is a vector of constants.
1473 bool IsConstMask = isa<ConstantVector>(Mask);
1474
1475 if (IsConstMask) {
1476 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1477 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1478 continue;
1479 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1480 "Ptr" + Twine(Idx));
1481 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1482 "Load" + Twine(Idx));
1483 VResult = Builder.CreateInsertElement(VResult, Load,
1484 Builder.getInt32(Idx),
1485 "Res" + Twine(Idx));
1486 }
1487 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1488 CI->replaceAllUsesWith(NewI);
1489 CI->eraseFromParent();
1490 return;
1491 }
1492
1493 PHINode *Phi = nullptr;
1494 Value *PrevPhi = UndefVal;
1495
1496 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1497
1498 // Fill the "else" block, created in the previous iteration
1499 //
1500 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1501 // %ToLoad1 = icmp eq i1 %Mask1, true
1502 // br i1 %ToLoad1, label %cond.load, label %else
1503 //
1504 if (Idx > 0) {
1505 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1506 Phi->addIncoming(VResult, CondBlock);
1507 Phi->addIncoming(PrevPhi, PrevIfBlock);
1508 PrevPhi = Phi;
1509 VResult = Phi;
1510 }
1511
1512 Value *Predicate = Builder.CreateExtractElement(Mask,
1513 Builder.getInt32(Idx),
1514 "Mask" + Twine(Idx));
1515 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1516 ConstantInt::get(Predicate->getType(), 1),
1517 "ToLoad" + Twine(Idx));
1518
1519 // Create "cond" block
1520 //
1521 // %EltAddr = getelementptr i32* %1, i32 0
1522 // %Elt = load i32* %EltAddr
1523 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1524 //
1525 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1526 Builder.SetInsertPoint(InsertPt);
1527
1528 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1529 "Ptr" + Twine(Idx));
1530 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1531 "Load" + Twine(Idx));
1532 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1533 "Res" + Twine(Idx));
1534
1535 // Create "else" block, fill it in the next iteration
1536 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1537 Builder.SetInsertPoint(InsertPt);
1538 Instruction *OldBr = IfBlock->getTerminator();
1539 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1540 OldBr->eraseFromParent();
1541 PrevIfBlock = IfBlock;
1542 IfBlock = NewIfBlock;
1543 }
1544
1545 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1546 Phi->addIncoming(VResult, CondBlock);
1547 Phi->addIncoming(PrevPhi, PrevIfBlock);
1548 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1549 CI->replaceAllUsesWith(NewI);
1550 CI->eraseFromParent();
1551}
1552
1553// Translate a masked scatter intrinsic, like
1554// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1555// <16 x i1> %Mask)
1556// to a chain of basic blocks, that stores element one-by-one if
1557// the appropriate mask bit is set.
1558//
1559// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1560// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1561// % ToStore0 = icmp eq i1 % Mask0, true
1562// br i1 %ToStore0, label %cond.store, label %else
1563//
1564// cond.store:
1565// % Elt0 = extractelement <16 x i32> %Src, i32 0
1566// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1567// store i32 %Elt0, i32* % Ptr0, align 4
1568// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001569//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001570// else:
1571// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1572// % ToStore1 = icmp eq i1 % Mask1, true
1573// br i1 % ToStore1, label %cond.store1, label %else2
1574//
1575// cond.store1:
1576// % Elt1 = extractelement <16 x i32> %Src, i32 1
1577// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1578// store i32 % Elt1, i32* % Ptr1, align 4
1579// br label %else2
1580// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001581static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001582 Value *Src = CI->getArgOperand(0);
1583 Value *Ptrs = CI->getArgOperand(1);
1584 Value *Alignment = CI->getArgOperand(2);
1585 Value *Mask = CI->getArgOperand(3);
1586
1587 assert(isa<VectorType>(Src->getType()) &&
1588 "Unexpected data type in masked scatter intrinsic");
1589 assert(isa<VectorType>(Ptrs->getType()) &&
1590 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1591 "Vector of pointers is expected in masked scatter intrinsic");
1592
1593 IRBuilder<> Builder(CI->getContext());
1594 Instruction *InsertPt = CI;
1595 BasicBlock *IfBlock = CI->getParent();
1596 Builder.SetInsertPoint(InsertPt);
1597 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1598
1599 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1600 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1601
1602 // Shorten the way if the mask is a vector of constants.
1603 bool IsConstMask = isa<ConstantVector>(Mask);
1604
1605 if (IsConstMask) {
1606 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1607 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1608 continue;
1609 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1610 "Elt" + Twine(Idx));
1611 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1612 "Ptr" + Twine(Idx));
1613 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1614 }
1615 CI->eraseFromParent();
1616 return;
1617 }
1618 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1619 // Fill the "else" block, created in the previous iteration
1620 //
1621 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1622 // % ToStore = icmp eq i1 % Mask1, true
1623 // br i1 % ToStore, label %cond.store, label %else
1624 //
1625 Value *Predicate = Builder.CreateExtractElement(Mask,
1626 Builder.getInt32(Idx),
1627 "Mask" + Twine(Idx));
1628 Value *Cmp =
1629 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1630 ConstantInt::get(Predicate->getType(), 1),
1631 "ToStore" + Twine(Idx));
1632
1633 // Create "cond" block
1634 //
1635 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1636 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1637 // %store i32 % Elt1, i32* % Ptr1
1638 //
1639 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1640 Builder.SetInsertPoint(InsertPt);
1641
1642 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1643 "Elt" + Twine(Idx));
1644 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1645 "Ptr" + Twine(Idx));
1646 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1647
1648 // Create "else" block, fill it in the next iteration
1649 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1650 Builder.SetInsertPoint(InsertPt);
1651 Instruction *OldBr = IfBlock->getTerminator();
1652 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1653 OldBr->eraseFromParent();
1654 IfBlock = NewIfBlock;
1655 }
1656 CI->eraseFromParent();
1657}
1658
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001659/// If counting leading or trailing zeros is an expensive operation and a zero
1660/// input is defined, add a check for zero to avoid calling the intrinsic.
1661///
1662/// We want to transform:
1663/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1664///
1665/// into:
1666/// entry:
1667/// %cmpz = icmp eq i64 %A, 0
1668/// br i1 %cmpz, label %cond.end, label %cond.false
1669/// cond.false:
1670/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1671/// br label %cond.end
1672/// cond.end:
1673/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1674///
1675/// If the transform is performed, return true and set ModifiedDT to true.
1676static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1677 const TargetLowering *TLI,
1678 const DataLayout *DL,
1679 bool &ModifiedDT) {
1680 if (!TLI || !DL)
1681 return false;
1682
1683 // If a zero input is undefined, it doesn't make sense to despeculate that.
1684 if (match(CountZeros->getOperand(1), m_One()))
1685 return false;
1686
1687 // If it's cheap to speculate, there's nothing to do.
1688 auto IntrinsicID = CountZeros->getIntrinsicID();
1689 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1690 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1691 return false;
1692
1693 // Only handle legal scalar cases. Anything else requires too much work.
1694 Type *Ty = CountZeros->getType();
1695 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001696 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001697 return false;
1698
1699 // The intrinsic will be sunk behind a compare against zero and branch.
1700 BasicBlock *StartBlock = CountZeros->getParent();
1701 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1702
1703 // Create another block after the count zero intrinsic. A PHI will be added
1704 // in this block to select the result of the intrinsic or the bit-width
1705 // constant if the input to the intrinsic is zero.
1706 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1707 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1708
1709 // Set up a builder to create a compare, conditional branch, and PHI.
1710 IRBuilder<> Builder(CountZeros->getContext());
1711 Builder.SetInsertPoint(StartBlock->getTerminator());
1712 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1713
1714 // Replace the unconditional branch that was created by the first split with
1715 // a compare against zero and a conditional branch.
1716 Value *Zero = Constant::getNullValue(Ty);
1717 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1718 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1719 StartBlock->getTerminator()->eraseFromParent();
1720
1721 // Create a PHI in the end block to select either the output of the intrinsic
1722 // or the bit width of the operand.
1723 Builder.SetInsertPoint(&EndBlock->front());
1724 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1725 CountZeros->replaceAllUsesWith(PN);
1726 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1727 PN->addIncoming(BitWidth, StartBlock);
1728 PN->addIncoming(CountZeros, CallBlock);
1729
1730 // We are explicitly handling the zero case, so we can set the intrinsic's
1731 // undefined zero argument to 'true'. This will also prevent reprocessing the
1732 // intrinsic; we only despeculate when a zero input is defined.
1733 CountZeros->setArgOperand(1, Builder.getTrue());
1734 ModifiedDT = true;
1735 return true;
1736}
1737
Sanjay Patelfc580a62015-09-21 23:03:16 +00001738bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001739 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001740
Chris Lattner7a277142011-01-15 07:14:54 +00001741 // Lower inline assembly if we can.
1742 // If we found an inline asm expession, and if the target knows how to
1743 // lower it to normal LLVM code, do so now.
1744 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1745 if (TLI->ExpandInlineAsm(CI)) {
1746 // Avoid invalidating the iterator.
1747 CurInstIterator = BB->begin();
1748 // Avoid processing instructions out of order, which could cause
1749 // reuse before a value is defined.
1750 SunkAddrs.clear();
1751 return true;
1752 }
1753 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001754 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001755 return true;
1756 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001757
John Brawn0dbcd652015-03-18 12:01:59 +00001758 // Align the pointer arguments to this call if the target thinks it's a good
1759 // idea
1760 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001761 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001762 for (auto &Arg : CI->arg_operands()) {
1763 // We want to align both objects whose address is used directly and
1764 // objects whose address is used in casts and GEPs, though it only makes
1765 // sense for GEPs if the offset is a multiple of the desired alignment and
1766 // if size - offset meets the size threshold.
1767 if (!Arg->getType()->isPointerTy())
1768 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001769 APInt Offset(DL->getPointerSizeInBits(
1770 cast<PointerType>(Arg->getType())->getAddressSpace()),
1771 0);
1772 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001773 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001774 if ((Offset2 & (PrefAlign-1)) != 0)
1775 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001776 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001777 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1778 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001779 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001780 // Global variables can only be aligned if they are defined in this
1781 // object (i.e. they are uniquely initialized in this object), and
1782 // over-aligning global variables that have an explicit section is
1783 // forbidden.
1784 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001785 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001786 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001787 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001788 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001789 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001790 }
1791 // If this is a memcpy (or similar) then we may be able to improve the
1792 // alignment
1793 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001794 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001795 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001796 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001797 if (Align > MI->getAlignment())
1798 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001799 }
1800 }
1801
Philip Reamesac115ed2016-03-09 23:13:12 +00001802 // If we have a cold call site, try to sink addressing computation into the
1803 // cold block. This interacts with our handling for loads and stores to
1804 // ensure that we can fold all uses of a potential addressing computation
1805 // into their uses. TODO: generalize this to work over profiling data
1806 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1807 for (auto &Arg : CI->arg_operands()) {
1808 if (!Arg->getType()->isPointerTy())
1809 continue;
1810 unsigned AS = Arg->getType()->getPointerAddressSpace();
1811 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1812 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001813
Eric Christopher4b7948e2010-03-11 02:41:03 +00001814 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001815 if (II) {
1816 switch (II->getIntrinsicID()) {
1817 default: break;
1818 case Intrinsic::objectsize: {
1819 // Lower all uses of llvm.objectsize.*
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001820 uint64_t Size;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001821 Type *ReturnTy = CI->getType();
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001822 Constant *RetVal = nullptr;
1823 ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1));
1824 ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min;
1825 if (getObjectSize(II->getArgOperand(0),
1826 Size, *DL, TLInfo, false, Mode)) {
1827 RetVal = ConstantInt::get(ReturnTy, Size);
1828 } else {
1829 RetVal = ConstantInt::get(ReturnTy,
1830 Mode == ObjSizeMode::Min ? 0 : -1ULL);
1831 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001832 // Substituting this can cause recursive simplifications, which can
1833 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1834 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001835 Value *CurValue = &*CurInstIterator;
1836 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001837
Sanjay Patel545a4562016-01-20 18:59:16 +00001838 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001839
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001840 // If the iterator instruction was recursively deleted, start over at the
1841 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001842 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001843 CurInstIterator = BB->begin();
1844 SunkAddrs.clear();
1845 }
1846 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001847 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001848 case Intrinsic::masked_load: {
1849 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001850 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001851 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001852 ModifiedDT = true;
1853 return true;
1854 }
1855 return false;
1856 }
1857 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001858 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001859 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001860 ModifiedDT = true;
1861 return true;
1862 }
1863 return false;
1864 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001865 case Intrinsic::masked_gather: {
1866 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001867 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001868 ModifiedDT = true;
1869 return true;
1870 }
1871 return false;
1872 }
1873 case Intrinsic::masked_scatter: {
1874 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001875 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001876 ModifiedDT = true;
1877 return true;
1878 }
1879 return false;
1880 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001881 case Intrinsic::aarch64_stlxr:
1882 case Intrinsic::aarch64_stxr: {
1883 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1884 if (!ExtVal || !ExtVal->hasOneUse() ||
1885 ExtVal->getParent() == CI->getParent())
1886 return false;
1887 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1888 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001889 // Mark this instruction as "inserted by CGP", so that other
1890 // optimizations don't touch it.
1891 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001892 return true;
1893 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001894 case Intrinsic::invariant_group_barrier:
1895 II->replaceAllUsesWith(II->getArgOperand(0));
1896 II->eraseFromParent();
1897 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001898
1899 case Intrinsic::cttz:
1900 case Intrinsic::ctlz:
1901 // If counting zeros is expensive, try to avoid it.
1902 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001903 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001904
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001905 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001906 // Unknown address space.
1907 // TODO: Target hook to pick which address space the intrinsic cares
1908 // about?
1909 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001910 SmallVector<Value*, 2> PtrOps;
1911 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001912 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001913 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001914 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001915 return true;
1916 }
Pete Cooper615fd892012-03-13 20:59:56 +00001917 }
1918
Eric Christopher4b7948e2010-03-11 02:41:03 +00001919 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001920 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001921
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001922 // Lower all default uses of _chk calls. This is very similar
1923 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001924 // to fortified library functions (e.g. __memcpy_chk) that have the default
1925 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001926 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001927 if (Value *V = Simplifier.optimizeCall(CI)) {
1928 CI->replaceAllUsesWith(V);
1929 CI->eraseFromParent();
1930 return true;
1931 }
1932 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001933}
Chris Lattner1b93be52011-01-15 07:25:29 +00001934
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001935/// Look for opportunities to duplicate return instructions to the predecessor
1936/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001937/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001938/// bb0:
1939/// %tmp0 = tail call i32 @f0()
1940/// br label %return
1941/// bb1:
1942/// %tmp1 = tail call i32 @f1()
1943/// br label %return
1944/// bb2:
1945/// %tmp2 = tail call i32 @f2()
1946/// br label %return
1947/// return:
1948/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1949/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001950/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001951///
1952/// =>
1953///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001954/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001955/// bb0:
1956/// %tmp0 = tail call i32 @f0()
1957/// ret i32 %tmp0
1958/// bb1:
1959/// %tmp1 = tail call i32 @f1()
1960/// ret i32 %tmp1
1961/// bb2:
1962/// %tmp2 = tail call i32 @f2()
1963/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001964/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001965bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001966 if (!TLI)
1967 return false;
1968
Michael Kuperstein71321562016-09-07 20:29:49 +00001969 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1970 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001971 return false;
1972
Craig Topperc0196b12014-04-14 00:51:57 +00001973 PHINode *PN = nullptr;
1974 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001975 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001976 if (V) {
1977 BCI = dyn_cast<BitCastInst>(V);
1978 if (BCI)
1979 V = BCI->getOperand(0);
1980
1981 PN = dyn_cast<PHINode>(V);
1982 if (!PN)
1983 return false;
1984 }
Evan Cheng0663f232011-03-21 01:19:09 +00001985
Cameron Zwarich4649f172011-03-24 04:52:10 +00001986 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001987 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001988
Cameron Zwarich4649f172011-03-24 04:52:10 +00001989 // Make sure there are no instructions between the PHI and return, or that the
1990 // return is the first instruction in the block.
1991 if (PN) {
1992 BasicBlock::iterator BI = BB->begin();
1993 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001994 if (&*BI == BCI)
1995 // Also skip over the bitcast.
1996 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001997 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001998 return false;
1999 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002000 BasicBlock::iterator BI = BB->begin();
2001 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002002 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002003 return false;
2004 }
Evan Cheng0663f232011-03-21 01:19:09 +00002005
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002006 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2007 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002008 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002009 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002010 if (PN) {
2011 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2012 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2013 // Make sure the phi value is indeed produced by the tail call.
2014 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002015 TLI->mayBeEmittedAsTailCall(CI) &&
2016 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002017 TailCalls.push_back(CI);
2018 }
2019 } else {
2020 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002021 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002022 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002023 continue;
2024
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002025 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002026 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2027 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002028 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2029 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002030 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002031
Cameron Zwarich4649f172011-03-24 04:52:10 +00002032 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002033 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2034 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002035 TailCalls.push_back(CI);
2036 }
Evan Cheng0663f232011-03-21 01:19:09 +00002037 }
2038
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002039 bool Changed = false;
2040 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2041 CallInst *CI = TailCalls[i];
2042 CallSite CS(CI);
2043
2044 // Conservatively require the attributes of the call to match those of the
2045 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002046 AttributeSet CalleeAttrs = CS.getAttributes();
2047 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002048 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002049 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002050 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002051 continue;
2052
2053 // Make sure the call instruction is followed by an unconditional branch to
2054 // the return block.
2055 BasicBlock *CallBB = CI->getParent();
2056 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2057 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2058 continue;
2059
2060 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002061 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002062 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002063 ++NumRetsDup;
2064 }
2065
2066 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002067 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002068 BB->eraseFromParent();
2069
2070 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002071}
2072
Chris Lattner728f9022008-11-25 07:09:13 +00002073//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002074// Memory Optimization
2075//===----------------------------------------------------------------------===//
2076
Chandler Carruthc8925912013-01-05 02:09:22 +00002077namespace {
2078
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002079/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002080/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002081struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002082 Value *BaseReg;
2083 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002084 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002085 void print(raw_ostream &OS) const;
2086 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002087
Chandler Carruthc8925912013-01-05 02:09:22 +00002088 bool operator==(const ExtAddrMode& O) const {
2089 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2090 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2091 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2092 }
2093};
2094
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002095#ifndef NDEBUG
2096static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2097 AM.print(OS);
2098 return OS;
2099}
2100#endif
2101
Chandler Carruthc8925912013-01-05 02:09:22 +00002102void ExtAddrMode::print(raw_ostream &OS) const {
2103 bool NeedPlus = false;
2104 OS << "[";
2105 if (BaseGV) {
2106 OS << (NeedPlus ? " + " : "")
2107 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002108 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002109 NeedPlus = true;
2110 }
2111
Richard Trieuc0f91212014-05-30 03:15:17 +00002112 if (BaseOffs) {
2113 OS << (NeedPlus ? " + " : "")
2114 << BaseOffs;
2115 NeedPlus = true;
2116 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002117
2118 if (BaseReg) {
2119 OS << (NeedPlus ? " + " : "")
2120 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002121 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002122 NeedPlus = true;
2123 }
2124 if (Scale) {
2125 OS << (NeedPlus ? " + " : "")
2126 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002127 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002128 }
2129
2130 OS << ']';
2131}
2132
2133#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002134LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002135 print(dbgs());
2136 dbgs() << '\n';
2137}
2138#endif
2139
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002140/// \brief This class provides transaction based operation on the IR.
2141/// Every change made through this class is recorded in the internal state and
2142/// can be undone (rollback) until commit is called.
2143class TypePromotionTransaction {
2144
2145 /// \brief This represents the common interface of the individual transaction.
2146 /// Each class implements the logic for doing one specific modification on
2147 /// the IR via the TypePromotionTransaction.
2148 class TypePromotionAction {
2149 protected:
2150 /// The Instruction modified.
2151 Instruction *Inst;
2152
2153 public:
2154 /// \brief Constructor of the action.
2155 /// The constructor performs the related action on the IR.
2156 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2157
2158 virtual ~TypePromotionAction() {}
2159
2160 /// \brief Undo the modification done by this action.
2161 /// When this method is called, the IR must be in the same state as it was
2162 /// before this action was applied.
2163 /// \pre Undoing the action works if and only if the IR is in the exact same
2164 /// state as it was directly after this action was applied.
2165 virtual void undo() = 0;
2166
2167 /// \brief Advocate every change made by this action.
2168 /// When the results on the IR of the action are to be kept, it is important
2169 /// to call this function, otherwise hidden information may be kept forever.
2170 virtual void commit() {
2171 // Nothing to be done, this action is not doing anything.
2172 }
2173 };
2174
2175 /// \brief Utility to remember the position of an instruction.
2176 class InsertionHandler {
2177 /// Position of an instruction.
2178 /// Either an instruction:
2179 /// - Is the first in a basic block: BB is used.
2180 /// - Has a previous instructon: PrevInst is used.
2181 union {
2182 Instruction *PrevInst;
2183 BasicBlock *BB;
2184 } Point;
2185 /// Remember whether or not the instruction had a previous instruction.
2186 bool HasPrevInstruction;
2187
2188 public:
2189 /// \brief Record the position of \p Inst.
2190 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002191 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002192 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2193 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002194 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002195 else
2196 Point.BB = Inst->getParent();
2197 }
2198
2199 /// \brief Insert \p Inst at the recorded position.
2200 void insert(Instruction *Inst) {
2201 if (HasPrevInstruction) {
2202 if (Inst->getParent())
2203 Inst->removeFromParent();
2204 Inst->insertAfter(Point.PrevInst);
2205 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002206 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002207 if (Inst->getParent())
2208 Inst->moveBefore(Position);
2209 else
2210 Inst->insertBefore(Position);
2211 }
2212 }
2213 };
2214
2215 /// \brief Move an instruction before another.
2216 class InstructionMoveBefore : public TypePromotionAction {
2217 /// Original position of the instruction.
2218 InsertionHandler Position;
2219
2220 public:
2221 /// \brief Move \p Inst before \p Before.
2222 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2223 : TypePromotionAction(Inst), Position(Inst) {
2224 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2225 Inst->moveBefore(Before);
2226 }
2227
2228 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002229 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002230 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2231 Position.insert(Inst);
2232 }
2233 };
2234
2235 /// \brief Set the operand of an instruction with a new value.
2236 class OperandSetter : public TypePromotionAction {
2237 /// Original operand of the instruction.
2238 Value *Origin;
2239 /// Index of the modified instruction.
2240 unsigned Idx;
2241
2242 public:
2243 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2244 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2245 : TypePromotionAction(Inst), Idx(Idx) {
2246 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2247 << "for:" << *Inst << "\n"
2248 << "with:" << *NewVal << "\n");
2249 Origin = Inst->getOperand(Idx);
2250 Inst->setOperand(Idx, NewVal);
2251 }
2252
2253 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002254 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2256 << "for: " << *Inst << "\n"
2257 << "with: " << *Origin << "\n");
2258 Inst->setOperand(Idx, Origin);
2259 }
2260 };
2261
2262 /// \brief Hide the operands of an instruction.
2263 /// Do as if this instruction was not using any of its operands.
2264 class OperandsHider : public TypePromotionAction {
2265 /// The list of original operands.
2266 SmallVector<Value *, 4> OriginalValues;
2267
2268 public:
2269 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2270 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2271 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2272 unsigned NumOpnds = Inst->getNumOperands();
2273 OriginalValues.reserve(NumOpnds);
2274 for (unsigned It = 0; It < NumOpnds; ++It) {
2275 // Save the current operand.
2276 Value *Val = Inst->getOperand(It);
2277 OriginalValues.push_back(Val);
2278 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002279 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002280 // that we are not willing to pay.
2281 Inst->setOperand(It, UndefValue::get(Val->getType()));
2282 }
2283 }
2284
2285 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002286 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002287 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2288 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2289 Inst->setOperand(It, OriginalValues[It]);
2290 }
2291 };
2292
2293 /// \brief Build a truncate instruction.
2294 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002295 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296 public:
2297 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2298 /// result.
2299 /// trunc Opnd to Ty.
2300 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2301 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002302 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2303 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002304 }
2305
Quentin Colombetac55b152014-09-16 22:36:07 +00002306 /// \brief Get the built value.
2307 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002308
2309 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002310 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002311 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2312 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2313 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002314 }
2315 };
2316
2317 /// \brief Build a sign extension instruction.
2318 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002319 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002320 public:
2321 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2322 /// result.
2323 /// sext Opnd to Ty.
2324 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002325 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002327 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2328 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002329 }
2330
Quentin Colombetac55b152014-09-16 22:36:07 +00002331 /// \brief Get the built value.
2332 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002333
2334 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002335 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002336 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2337 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2338 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002339 }
2340 };
2341
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002342 /// \brief Build a zero extension instruction.
2343 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002344 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002345 public:
2346 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2347 /// result.
2348 /// zext Opnd to Ty.
2349 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002350 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002351 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002352 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2353 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002354 }
2355
Quentin Colombetac55b152014-09-16 22:36:07 +00002356 /// \brief Get the built value.
2357 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002358
2359 /// \brief Remove the built instruction.
2360 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002361 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2362 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2363 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002364 }
2365 };
2366
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002367 /// \brief Mutate an instruction to another type.
2368 class TypeMutator : public TypePromotionAction {
2369 /// Record the original type.
2370 Type *OrigTy;
2371
2372 public:
2373 /// \brief Mutate the type of \p Inst into \p NewTy.
2374 TypeMutator(Instruction *Inst, Type *NewTy)
2375 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2376 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2377 << "\n");
2378 Inst->mutateType(NewTy);
2379 }
2380
2381 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002382 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002383 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2384 << "\n");
2385 Inst->mutateType(OrigTy);
2386 }
2387 };
2388
2389 /// \brief Replace the uses of an instruction by another instruction.
2390 class UsesReplacer : public TypePromotionAction {
2391 /// Helper structure to keep track of the replaced uses.
2392 struct InstructionAndIdx {
2393 /// The instruction using the instruction.
2394 Instruction *Inst;
2395 /// The index where this instruction is used for Inst.
2396 unsigned Idx;
2397 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2398 : Inst(Inst), Idx(Idx) {}
2399 };
2400
2401 /// Keep track of the original uses (pair Instruction, Index).
2402 SmallVector<InstructionAndIdx, 4> OriginalUses;
2403 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2404
2405 public:
2406 /// \brief Replace all the use of \p Inst by \p New.
2407 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2408 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2409 << "\n");
2410 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002411 for (Use &U : Inst->uses()) {
2412 Instruction *UserI = cast<Instruction>(U.getUser());
2413 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002414 }
2415 // Now, we can replace the uses.
2416 Inst->replaceAllUsesWith(New);
2417 }
2418
2419 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002420 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002421 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2422 for (use_iterator UseIt = OriginalUses.begin(),
2423 EndIt = OriginalUses.end();
2424 UseIt != EndIt; ++UseIt) {
2425 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2426 }
2427 }
2428 };
2429
2430 /// \brief Remove an instruction from the IR.
2431 class InstructionRemover : public TypePromotionAction {
2432 /// Original position of the instruction.
2433 InsertionHandler Inserter;
2434 /// Helper structure to hide all the link to the instruction. In other
2435 /// words, this helps to do as if the instruction was removed.
2436 OperandsHider Hider;
2437 /// Keep track of the uses replaced, if any.
2438 UsesReplacer *Replacer;
2439
2440 public:
2441 /// \brief Remove all reference of \p Inst and optinally replace all its
2442 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002443 /// \pre If !Inst->use_empty(), then New != nullptr
2444 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002446 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002447 if (New)
2448 Replacer = new UsesReplacer(Inst, New);
2449 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2450 Inst->removeFromParent();
2451 }
2452
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002453 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002454
2455 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002456 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002457
2458 /// \brief Resurrect the instruction and reassign it to the proper uses if
2459 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002460 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002461 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2462 Inserter.insert(Inst);
2463 if (Replacer)
2464 Replacer->undo();
2465 Hider.undo();
2466 }
2467 };
2468
2469public:
2470 /// Restoration point.
2471 /// The restoration point is a pointer to an action instead of an iterator
2472 /// because the iterator may be invalidated but not the pointer.
2473 typedef const TypePromotionAction *ConstRestorationPt;
2474 /// Advocate every changes made in that transaction.
2475 void commit();
2476 /// Undo all the changes made after the given point.
2477 void rollback(ConstRestorationPt Point);
2478 /// Get the current restoration point.
2479 ConstRestorationPt getRestorationPoint() const;
2480
2481 /// \name API for IR modification with state keeping to support rollback.
2482 /// @{
2483 /// Same as Instruction::setOperand.
2484 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2485 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002486 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002487 /// Same as Value::replaceAllUsesWith.
2488 void replaceAllUsesWith(Instruction *Inst, Value *New);
2489 /// Same as Value::mutateType.
2490 void mutateType(Instruction *Inst, Type *NewTy);
2491 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002492 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002493 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002494 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002495 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002496 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497 /// Same as Instruction::moveBefore.
2498 void moveBefore(Instruction *Inst, Instruction *Before);
2499 /// @}
2500
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002501private:
2502 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002503 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2504 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002505};
2506
2507void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2508 Value *NewVal) {
2509 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002510 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511}
2512
2513void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2514 Value *NewVal) {
2515 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002516 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002517}
2518
2519void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2520 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002521 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002522}
2523
2524void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002525 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002526}
2527
Quentin Colombetac55b152014-09-16 22:36:07 +00002528Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2529 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002530 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002531 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002532 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002533 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002534}
2535
Quentin Colombetac55b152014-09-16 22:36:07 +00002536Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2537 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002538 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002539 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002540 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002541 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002542}
2543
Quentin Colombetac55b152014-09-16 22:36:07 +00002544Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2545 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002546 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002547 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002548 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002549 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002550}
2551
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002552void TypePromotionTransaction::moveBefore(Instruction *Inst,
2553 Instruction *Before) {
2554 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002555 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002556}
2557
2558TypePromotionTransaction::ConstRestorationPt
2559TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002560 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002561}
2562
2563void TypePromotionTransaction::commit() {
2564 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002565 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002566 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002567 Actions.clear();
2568}
2569
2570void TypePromotionTransaction::rollback(
2571 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002572 while (!Actions.empty() && Point != Actions.back().get()) {
2573 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002574 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002575 }
2576}
2577
Chandler Carruthc8925912013-01-05 02:09:22 +00002578/// \brief A helper class for matching addressing modes.
2579///
2580/// This encapsulates the logic for matching the target-legal addressing modes.
2581class AddressingModeMatcher {
2582 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002583 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002584 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002585 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002586
2587 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2588 /// the memory instruction that we're computing this address for.
2589 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002590 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002591 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002592
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002593 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002594 /// part of the return value of this addressing mode matching stuff.
2595 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002596
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002597 /// The instructions inserted by other CodeGenPrepare optimizations.
2598 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599 /// A map from the instructions to their type before promotion.
2600 InstrToOrigTy &PromotedInsts;
2601 /// The ongoing transaction where every action should be registered.
2602 TypePromotionTransaction &TPT;
2603
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002604 /// This is set to true when we should not do profitability checks.
2605 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002606 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002607
Eric Christopherd75c00c2015-02-26 22:38:34 +00002608 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002609 const TargetMachine &TM, Type *AT, unsigned AS,
2610 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002611 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002612 InstrToOrigTy &PromotedInsts,
2613 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002614 : AddrModeInsts(AMI), TM(TM),
2615 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2616 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002617 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2618 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2619 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002620 IgnoreProfitability = false;
2621 }
2622public:
Stephen Lin837bba12013-07-15 17:55:02 +00002623
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002624 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002625 /// give an access type of AccessTy. This returns a list of involved
2626 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002627 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002628 /// optimizations.
2629 /// \p PromotedInsts maps the instructions to their type before promotion.
2630 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002631 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002632 Instruction *MemoryInst,
2633 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002634 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002635 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002636 InstrToOrigTy &PromotedInsts,
2637 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002638 ExtAddrMode Result;
2639
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002640 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002641 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002642 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002643 (void)Success; assert(Success && "Couldn't select *anything*?");
2644 return Result;
2645 }
2646private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002647 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2648 bool matchAddr(Value *V, unsigned Depth);
2649 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002650 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002651 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002652 ExtAddrMode &AMBefore,
2653 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002654 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2655 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002656 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002657};
2658
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002659/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002660/// Return true and update AddrMode if this addr mode is legal for the target,
2661/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002662bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002663 unsigned Depth) {
2664 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2665 // mode. Just process that directly.
2666 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002667 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002668
Chandler Carruthc8925912013-01-05 02:09:22 +00002669 // If the scale is 0, it takes nothing to add this.
2670 if (Scale == 0)
2671 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002672
Chandler Carruthc8925912013-01-05 02:09:22 +00002673 // If we already have a scale of this value, we can add to it, otherwise, we
2674 // need an available scale field.
2675 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2676 return false;
2677
2678 ExtAddrMode TestAddrMode = AddrMode;
2679
2680 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2681 // [A+B + A*7] -> [B+A*8].
2682 TestAddrMode.Scale += Scale;
2683 TestAddrMode.ScaledReg = ScaleReg;
2684
2685 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002686 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002687 return false;
2688
2689 // It was legal, so commit it.
2690 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002691
Chandler Carruthc8925912013-01-05 02:09:22 +00002692 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2693 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2694 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002695 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002696 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2697 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2698 TestAddrMode.ScaledReg = AddLHS;
2699 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002700
Chandler Carruthc8925912013-01-05 02:09:22 +00002701 // If this addressing mode is legal, commit it and remember that we folded
2702 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002703 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002704 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2705 AddrMode = TestAddrMode;
2706 return true;
2707 }
2708 }
2709
2710 // Otherwise, not (x+c)*scale, just return what we have.
2711 return true;
2712}
2713
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002714/// This is a little filter, which returns true if an addressing computation
2715/// involving I might be folded into a load/store accessing it.
2716/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002717/// the set of instructions that MatchOperationAddr can.
2718static bool MightBeFoldableInst(Instruction *I) {
2719 switch (I->getOpcode()) {
2720 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002721 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002722 // Don't touch identity bitcasts.
2723 if (I->getType() == I->getOperand(0)->getType())
2724 return false;
2725 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2726 case Instruction::PtrToInt:
2727 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2728 return true;
2729 case Instruction::IntToPtr:
2730 // We know the input is intptr_t, so this is foldable.
2731 return true;
2732 case Instruction::Add:
2733 return true;
2734 case Instruction::Mul:
2735 case Instruction::Shl:
2736 // Can only handle X*C and X << C.
2737 return isa<ConstantInt>(I->getOperand(1));
2738 case Instruction::GetElementPtr:
2739 return true;
2740 default:
2741 return false;
2742 }
2743}
2744
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002745/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2746/// \note \p Val is assumed to be the product of some type promotion.
2747/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2748/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002749static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2750 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002751 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2752 if (!PromotedInst)
2753 return false;
2754 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2755 // If the ISDOpcode is undefined, it was undefined before the promotion.
2756 if (!ISDOpcode)
2757 return true;
2758 // Otherwise, check if the promoted instruction is legal or not.
2759 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002760 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002761}
2762
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002763/// \brief Hepler class to perform type promotion.
2764class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002765 /// \brief Utility function to check whether or not a sign or zero extension
2766 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2767 /// either using the operands of \p Inst or promoting \p Inst.
2768 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002769 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002770 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002771 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002772 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002773 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002774 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002775 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002776 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2777 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002778
2779 /// \brief Utility function to determine if \p OpIdx should be promoted when
2780 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002781 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002782 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002783 }
2784
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002785 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002786 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002787 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002788 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002789 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002790 /// Newly added extensions are inserted in \p Exts.
2791 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002792 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002793 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002794 static Value *promoteOperandForTruncAndAnyExt(
2795 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002796 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002797 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002798 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002799
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002800 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002801 /// operand is promotable and is not a supported trunc or sext.
2802 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002803 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002804 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002805 /// Newly added extensions are inserted in \p Exts.
2806 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002807 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002808 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002809 static Value *promoteOperandForOther(Instruction *Ext,
2810 TypePromotionTransaction &TPT,
2811 InstrToOrigTy &PromotedInsts,
2812 unsigned &CreatedInstsCost,
2813 SmallVectorImpl<Instruction *> *Exts,
2814 SmallVectorImpl<Instruction *> *Truncs,
2815 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002816
2817 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002818 static Value *signExtendOperandForOther(
2819 Instruction *Ext, TypePromotionTransaction &TPT,
2820 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2821 SmallVectorImpl<Instruction *> *Exts,
2822 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2823 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2824 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002825 }
2826
2827 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002828 static Value *zeroExtendOperandForOther(
2829 Instruction *Ext, TypePromotionTransaction &TPT,
2830 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2831 SmallVectorImpl<Instruction *> *Exts,
2832 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2833 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2834 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002835 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002836
2837public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002838 /// Type for the utility function that promotes the operand of Ext.
2839 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002840 InstrToOrigTy &PromotedInsts,
2841 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002842 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002843 SmallVectorImpl<Instruction *> *Truncs,
2844 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002845 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2846 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002847 /// \return NULL if no promotable action is possible with the current
2848 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002849 /// \p InsertedInsts keeps track of all the instructions inserted by the
2850 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002851 /// because we do not want to promote these instructions as CodeGenPrepare
2852 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2853 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002854 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002855 const TargetLowering &TLI,
2856 const InstrToOrigTy &PromotedInsts);
2857};
2858
2859bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002860 Type *ConsideredExtType,
2861 const InstrToOrigTy &PromotedInsts,
2862 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002863 // The promotion helper does not know how to deal with vector types yet.
2864 // To be able to fix that, we would need to fix the places where we
2865 // statically extend, e.g., constants and such.
2866 if (Inst->getType()->isVectorTy())
2867 return false;
2868
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002869 // We can always get through zext.
2870 if (isa<ZExtInst>(Inst))
2871 return true;
2872
2873 // sext(sext) is ok too.
2874 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002875 return true;
2876
2877 // We can get through binary operator, if it is legal. In other words, the
2878 // binary operator must have a nuw or nsw flag.
2879 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2880 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002881 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2882 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002883 return true;
2884
2885 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002886 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002887 if (!isa<TruncInst>(Inst))
2888 return false;
2889
2890 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002891 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002892 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002893 if (!OpndVal->getType()->isIntegerTy() ||
2894 OpndVal->getType()->getIntegerBitWidth() >
2895 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002896 return false;
2897
2898 // If the operand of the truncate is not an instruction, we will not have
2899 // any information on the dropped bits.
2900 // (Actually we could for constant but it is not worth the extra logic).
2901 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2902 if (!Opnd)
2903 return false;
2904
2905 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002906 // I.e., check that trunc just drops extended bits of the same kind of
2907 // the extension.
2908 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002909 const Type *OpndType;
2910 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002911 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2912 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002913 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2914 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002915 else
2916 return false;
2917
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002918 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002919 return Inst->getType()->getIntegerBitWidth() >=
2920 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002921}
2922
2923TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002924 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002925 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002926 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2927 "Unexpected instruction type");
2928 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2929 Type *ExtTy = Ext->getType();
2930 bool IsSExt = isa<SExtInst>(Ext);
2931 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002932 // get through.
2933 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002934 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002935 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002936
2937 // Do not promote if the operand has been added by codegenprepare.
2938 // Otherwise, it means we are undoing an optimization that is likely to be
2939 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002940 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002941 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002942
2943 // SExt or Trunc instructions.
2944 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002945 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2946 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002947 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002948
2949 // Regular instruction.
2950 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002951 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002952 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002953 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002954}
2955
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002956Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002957 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002958 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002959 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002960 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002961 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2962 // get through it and this method should not be called.
2963 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002964 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002965 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002966 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002967 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002968 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002969 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002970 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002971 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2972 TPT.replaceAllUsesWith(SExt, ZExt);
2973 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002974 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002975 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002976 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2977 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002978 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2979 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002980 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002981
2982 // Remove dead code.
2983 if (SExtOpnd->use_empty())
2984 TPT.eraseInstruction(SExtOpnd);
2985
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002986 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002987 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002988 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002989 if (ExtInst) {
2990 if (Exts)
2991 Exts->push_back(ExtInst);
2992 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2993 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002994 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002995 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002996
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002997 // At this point we have: ext ty opnd to ty.
2998 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2999 Value *NextVal = ExtInst->getOperand(0);
3000 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003001 return NextVal;
3002}
3003
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003004Value *TypePromotionHelper::promoteOperandForOther(
3005 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003006 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003007 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003008 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3009 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003010 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003011 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003012 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003013 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003014 if (!ExtOpnd->hasOneUse()) {
3015 // ExtOpnd will be promoted.
3016 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003017 // promoted version.
3018 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003019 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003020 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3021 ITrunc->removeFromParent();
3022 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003023 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003024 if (Truncs)
3025 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003026 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003027
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003028 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003029 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003030 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003031 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003032 }
3033
3034 // Get through the Instruction:
3035 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003036 // 2. Replace the uses of Ext by Inst.
3037 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003038
3039 // Remember the original type of the instruction before promotion.
3040 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003041 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3042 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003043 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003044 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003045 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003046 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003047 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003048 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003049
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003050 DEBUG(dbgs() << "Propagate Ext to operands\n");
3051 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003052 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003053 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3054 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3055 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003056 DEBUG(dbgs() << "No need to propagate\n");
3057 continue;
3058 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003059 // Check if we can statically extend the operand.
3060 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003061 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003062 DEBUG(dbgs() << "Statically extend\n");
3063 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3064 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3065 : Cst->getValue().zext(BitWidth);
3066 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003067 continue;
3068 }
3069 // UndefValue are typed, so we have to statically sign extend them.
3070 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003071 DEBUG(dbgs() << "Statically extend\n");
3072 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003073 continue;
3074 }
3075
3076 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003077 // Check if Ext was reused to extend an operand.
3078 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003079 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003080 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003081 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3082 : TPT.createZExt(Ext, Opnd, Ext->getType());
3083 if (!isa<Instruction>(ValForExtOpnd)) {
3084 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3085 continue;
3086 }
3087 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003088 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003089 if (Exts)
3090 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003091 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003092
3093 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003094 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3095 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003096 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003097 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003098 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003099 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003100 if (ExtForOpnd == Ext) {
3101 DEBUG(dbgs() << "Extension is useless now\n");
3102 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003103 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003104 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003105}
3106
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003107/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003108/// \p NewCost gives the cost of extension instructions created by the
3109/// promotion.
3110/// \p OldCost gives the cost of extension instructions before the promotion
3111/// plus the number of instructions that have been
3112/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003113/// \p PromotedOperand is the value that has been promoted.
3114/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003115bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003116 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3117 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3118 // The cost of the new extensions is greater than the cost of the
3119 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003120 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003121 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003122 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003123 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003124 return true;
3125 // The promotion is neutral but it may help folding the sign extension in
3126 // loads for instance.
3127 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003128 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003129}
3130
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003131/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003132/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003133/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003134/// If \p MovedAway is not NULL, it contains the information of whether or
3135/// not AddrInst has to be folded into the addressing mode on success.
3136/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3137/// because it has been moved away.
3138/// Thus AddrInst must not be added in the matched instructions.
3139/// This state can happen when AddrInst is a sext, since it may be moved away.
3140/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3141/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003142bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003143 unsigned Depth,
3144 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003145 // Avoid exponential behavior on extremely deep expression trees.
3146 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003147
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003148 // By default, all matched instructions stay in place.
3149 if (MovedAway)
3150 *MovedAway = false;
3151
Chandler Carruthc8925912013-01-05 02:09:22 +00003152 switch (Opcode) {
3153 case Instruction::PtrToInt:
3154 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003155 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003156 case Instruction::IntToPtr: {
3157 auto AS = AddrInst->getType()->getPointerAddressSpace();
3158 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003159 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003160 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003161 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003162 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003163 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003164 case Instruction::BitCast:
3165 // BitCast is always a noop, and we can handle it as long as it is
3166 // int->int or pointer->pointer (we don't want int<->fp or something).
3167 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3168 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3169 // Don't touch identity bitcasts. These were probably put here by LSR,
3170 // and we don't want to mess around with them. Assume it knows what it
3171 // is doing.
3172 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003173 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003174 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003175 case Instruction::AddrSpaceCast: {
3176 unsigned SrcAS
3177 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3178 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3179 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003180 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003181 return false;
3182 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003183 case Instruction::Add: {
3184 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3185 ExtAddrMode BackupAddrMode = AddrMode;
3186 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003187 // Start a transaction at this point.
3188 // The LHS may match but not the RHS.
3189 // Therefore, we need a higher level restoration point to undo partially
3190 // matched operation.
3191 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3192 TPT.getRestorationPoint();
3193
Sanjay Patelfc580a62015-09-21 23:03:16 +00003194 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3195 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003196 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003197
Chandler Carruthc8925912013-01-05 02:09:22 +00003198 // Restore the old addr mode info.
3199 AddrMode = BackupAddrMode;
3200 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003201 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003202
Chandler Carruthc8925912013-01-05 02:09:22 +00003203 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003204 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3205 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003206 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003207
Chandler Carruthc8925912013-01-05 02:09:22 +00003208 // Otherwise we definitely can't merge the ADD in.
3209 AddrMode = BackupAddrMode;
3210 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003211 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003212 break;
3213 }
3214 //case Instruction::Or:
3215 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3216 //break;
3217 case Instruction::Mul:
3218 case Instruction::Shl: {
3219 // Can only handle X*C and X << C.
3220 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003221 if (!RHS)
3222 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003223 int64_t Scale = RHS->getSExtValue();
3224 if (Opcode == Instruction::Shl)
3225 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003226
Sanjay Patelfc580a62015-09-21 23:03:16 +00003227 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003228 }
3229 case Instruction::GetElementPtr: {
3230 // Scan the GEP. We check it if it contains constant offsets and at most
3231 // one variable offset.
3232 int VariableOperand = -1;
3233 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003234
Chandler Carruthc8925912013-01-05 02:09:22 +00003235 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003236 gep_type_iterator GTI = gep_type_begin(AddrInst);
3237 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3238 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003239 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003240 unsigned Idx =
3241 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3242 ConstantOffset += SL->getElementOffset(Idx);
3243 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003244 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003245 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3246 ConstantOffset += CI->getSExtValue()*TypeSize;
3247 } else if (TypeSize) { // Scales of zero don't do anything.
3248 // We only allow one variable index at the moment.
3249 if (VariableOperand != -1)
3250 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003251
Chandler Carruthc8925912013-01-05 02:09:22 +00003252 // Remember the variable index.
3253 VariableOperand = i;
3254 VariableScale = TypeSize;
3255 }
3256 }
3257 }
Stephen Lin837bba12013-07-15 17:55:02 +00003258
Chandler Carruthc8925912013-01-05 02:09:22 +00003259 // A common case is for the GEP to only do a constant offset. In this case,
3260 // just add it to the disp field and check validity.
3261 if (VariableOperand == -1) {
3262 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003263 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003264 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003265 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003266 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003267 return true;
3268 }
3269 AddrMode.BaseOffs -= ConstantOffset;
3270 return false;
3271 }
3272
3273 // Save the valid addressing mode in case we can't match.
3274 ExtAddrMode BackupAddrMode = AddrMode;
3275 unsigned OldSize = AddrModeInsts.size();
3276
3277 // See if the scale and offset amount is valid for this target.
3278 AddrMode.BaseOffs += ConstantOffset;
3279
3280 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003281 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003282 // If it couldn't be matched, just stuff the value in a register.
3283 if (AddrMode.HasBaseReg) {
3284 AddrMode = BackupAddrMode;
3285 AddrModeInsts.resize(OldSize);
3286 return false;
3287 }
3288 AddrMode.HasBaseReg = true;
3289 AddrMode.BaseReg = AddrInst->getOperand(0);
3290 }
3291
3292 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003293 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003294 Depth)) {
3295 // If it couldn't be matched, try stuffing the base into a register
3296 // instead of matching it, and retrying the match of the scale.
3297 AddrMode = BackupAddrMode;
3298 AddrModeInsts.resize(OldSize);
3299 if (AddrMode.HasBaseReg)
3300 return false;
3301 AddrMode.HasBaseReg = true;
3302 AddrMode.BaseReg = AddrInst->getOperand(0);
3303 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003304 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003305 VariableScale, Depth)) {
3306 // If even that didn't work, bail.
3307 AddrMode = BackupAddrMode;
3308 AddrModeInsts.resize(OldSize);
3309 return false;
3310 }
3311 }
3312
3313 return true;
3314 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003315 case Instruction::SExt:
3316 case Instruction::ZExt: {
3317 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3318 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003319 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003320
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003321 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003322 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003323 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003324 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003325 if (!TPH)
3326 return false;
3327
3328 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3329 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003330 unsigned CreatedInstsCost = 0;
3331 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003332 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003333 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003334 // SExt has been moved away.
3335 // Thus either it will be rematched later in the recursive calls or it is
3336 // gone. Anyway, we must not fold it into the addressing mode at this point.
3337 // E.g.,
3338 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003339 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003340 // addr = gep base, idx
3341 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003342 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003343 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3344 // addr = gep base, op <- match
3345 if (MovedAway)
3346 *MovedAway = true;
3347
3348 assert(PromotedOperand &&
3349 "TypePromotionHelper should have filtered out those cases");
3350
3351 ExtAddrMode BackupAddrMode = AddrMode;
3352 unsigned OldSize = AddrModeInsts.size();
3353
Sanjay Patelfc580a62015-09-21 23:03:16 +00003354 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003355 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003356 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003357 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003358 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003359 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003360 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003361 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003362 AddrMode = BackupAddrMode;
3363 AddrModeInsts.resize(OldSize);
3364 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3365 TPT.rollback(LastKnownGood);
3366 return false;
3367 }
3368 return true;
3369 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003370 }
3371 return false;
3372}
3373
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003374/// If we can, try to add the value of 'Addr' into the current addressing mode.
3375/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3376/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3377/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003378///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003379bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003380 // Start a transaction at this point that we will rollback if the matching
3381 // fails.
3382 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3383 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003384 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3385 // Fold in immediates if legal for the target.
3386 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003387 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003388 return true;
3389 AddrMode.BaseOffs -= CI->getSExtValue();
3390 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3391 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003392 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003393 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003394 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003395 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003396 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003397 }
3398 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3399 ExtAddrMode BackupAddrMode = AddrMode;
3400 unsigned OldSize = AddrModeInsts.size();
3401
3402 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003403 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003404 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003405 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003406 // to check here.
3407 if (MovedAway)
3408 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003409 // Okay, it's possible to fold this. Check to see if it is actually
3410 // *profitable* to do so. We use a simple cost model to avoid increasing
3411 // register pressure too much.
3412 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003413 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003414 AddrModeInsts.push_back(I);
3415 return true;
3416 }
Stephen Lin837bba12013-07-15 17:55:02 +00003417
Chandler Carruthc8925912013-01-05 02:09:22 +00003418 // It isn't profitable to do this, roll back.
3419 //cerr << "NOT FOLDING: " << *I;
3420 AddrMode = BackupAddrMode;
3421 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003422 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003423 }
3424 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003425 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003426 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003427 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003428 } else if (isa<ConstantPointerNull>(Addr)) {
3429 // Null pointer gets folded without affecting the addressing mode.
3430 return true;
3431 }
3432
3433 // Worse case, the target should support [reg] addressing modes. :)
3434 if (!AddrMode.HasBaseReg) {
3435 AddrMode.HasBaseReg = true;
3436 AddrMode.BaseReg = Addr;
3437 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003438 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003439 return true;
3440 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003441 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003442 }
3443
3444 // If the base register is already taken, see if we can do [r+r].
3445 if (AddrMode.Scale == 0) {
3446 AddrMode.Scale = 1;
3447 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003448 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003449 return true;
3450 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003451 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003452 }
3453 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003454 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003455 return false;
3456}
3457
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003458/// Check to see if all uses of OpVal by the specified inline asm call are due
3459/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003460static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003461 const TargetMachine &TM) {
3462 const Function *F = CI->getParent()->getParent();
3463 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3464 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003465 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003466 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3467 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003468 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3469 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003470
Chandler Carruthc8925912013-01-05 02:09:22 +00003471 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003472 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003473
3474 // If this asm operand is our Value*, and if it isn't an indirect memory
3475 // operand, we can't fold it!
3476 if (OpInfo.CallOperandVal == OpVal &&
3477 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3478 !OpInfo.isIndirect))
3479 return false;
3480 }
3481
3482 return true;
3483}
3484
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003485/// Recursively walk all the uses of I until we find a memory use.
3486/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003487/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003488static bool FindAllMemoryUses(
3489 Instruction *I,
3490 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3491 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003492 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003493 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003494 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003495
Chandler Carruthc8925912013-01-05 02:09:22 +00003496 // If this is an obviously unfoldable instruction, bail out.
3497 if (!MightBeFoldableInst(I))
3498 return true;
3499
Philip Reamesac115ed2016-03-09 23:13:12 +00003500 const bool OptSize = I->getFunction()->optForSize();
3501
Chandler Carruthc8925912013-01-05 02:09:22 +00003502 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003503 for (Use &U : I->uses()) {
3504 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003505
Chandler Carruthcdf47882014-03-09 03:16:01 +00003506 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3507 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003508 continue;
3509 }
Stephen Lin837bba12013-07-15 17:55:02 +00003510
Chandler Carruthcdf47882014-03-09 03:16:01 +00003511 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3512 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003513 if (opNo == 0) return true; // Storing addr, not into addr.
3514 MemoryUses.push_back(std::make_pair(SI, opNo));
3515 continue;
3516 }
Stephen Lin837bba12013-07-15 17:55:02 +00003517
Chandler Carruthcdf47882014-03-09 03:16:01 +00003518 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003519 // If this is a cold call, we can sink the addressing calculation into
3520 // the cold path. See optimizeCallInst
3521 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3522 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003523
Chandler Carruthc8925912013-01-05 02:09:22 +00003524 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3525 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003526
Chandler Carruthc8925912013-01-05 02:09:22 +00003527 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003528 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003529 return true;
3530 continue;
3531 }
Stephen Lin837bba12013-07-15 17:55:02 +00003532
Eric Christopher11e4df72015-02-26 22:38:43 +00003533 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003534 return true;
3535 }
3536
3537 return false;
3538}
3539
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003540/// Return true if Val is already known to be live at the use site that we're
3541/// folding it into. If so, there is no cost to include it in the addressing
3542/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3543/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003544bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003545 Value *KnownLive2) {
3546 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003547 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003548 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003549
Chandler Carruthc8925912013-01-05 02:09:22 +00003550 // All values other than instructions and arguments (e.g. constants) are live.
3551 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003552
Chandler Carruthc8925912013-01-05 02:09:22 +00003553 // If Val is a constant sized alloca in the entry block, it is live, this is
3554 // true because it is just a reference to the stack/frame pointer, which is
3555 // live for the whole function.
3556 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3557 if (AI->isStaticAlloca())
3558 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003559
Chandler Carruthc8925912013-01-05 02:09:22 +00003560 // Check to see if this value is already used in the memory instruction's
3561 // block. If so, it's already live into the block at the very least, so we
3562 // can reasonably fold it.
3563 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3564}
3565
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003566/// It is possible for the addressing mode of the machine to fold the specified
3567/// instruction into a load or store that ultimately uses it.
3568/// However, the specified instruction has multiple uses.
3569/// Given this, it may actually increase register pressure to fold it
3570/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003571///
3572/// X = ...
3573/// Y = X+1
3574/// use(Y) -> nonload/store
3575/// Z = Y+1
3576/// load Z
3577///
3578/// In this case, Y has multiple uses, and can be folded into the load of Z
3579/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3580/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3581/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3582/// number of computations either.
3583///
3584/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3585/// X was live across 'load Z' for other reasons, we actually *would* want to
3586/// fold the addressing mode in the Z case. This would make Y die earlier.
3587bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003588isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003589 ExtAddrMode &AMAfter) {
3590 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003591
Chandler Carruthc8925912013-01-05 02:09:22 +00003592 // AMBefore is the addressing mode before this instruction was folded into it,
3593 // and AMAfter is the addressing mode after the instruction was folded. Get
3594 // the set of registers referenced by AMAfter and subtract out those
3595 // referenced by AMBefore: this is the set of values which folding in this
3596 // address extends the lifetime of.
3597 //
3598 // Note that there are only two potential values being referenced here,
3599 // BaseReg and ScaleReg (global addresses are always available, as are any
3600 // folded immediates).
3601 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003602
Chandler Carruthc8925912013-01-05 02:09:22 +00003603 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3604 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003605 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003606 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003607 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003608 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003609
3610 // If folding this instruction (and it's subexprs) didn't extend any live
3611 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003612 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003613 return true;
3614
Philip Reamesac115ed2016-03-09 23:13:12 +00003615 // If all uses of this instruction can have the address mode sunk into them,
3616 // we can remove the addressing mode and effectively trade one live register
3617 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003618 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003619 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3620 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003621 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003622 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003623
Chandler Carruthc8925912013-01-05 02:09:22 +00003624 // Now that we know that all uses of this instruction are part of a chain of
3625 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003626 // into a memory use, loop over each of these memory operation uses and see
3627 // if they could *actually* fold the instruction. The assumption is that
3628 // addressing modes are cheap and that duplicating the computation involved
3629 // many times is worthwhile, even on a fastpath. For sinking candidates
3630 // (i.e. cold call sites), this serves as a way to prevent excessive code
3631 // growth since most architectures have some reasonable small and fast way to
3632 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003633 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3634 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3635 Instruction *User = MemoryUses[i].first;
3636 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003637
Chandler Carruthc8925912013-01-05 02:09:22 +00003638 // Get the access type of this use. If the use isn't a pointer, we don't
3639 // know what it accesses.
3640 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003641 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3642 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003643 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003644 Type *AddressAccessTy = AddrTy->getElementType();
3645 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003646
Chandler Carruthc8925912013-01-05 02:09:22 +00003647 // Do a match against the root of this address, ignoring profitability. This
3648 // will tell us if the addressing mode for the memory operation will
3649 // *actually* cover the shared instruction.
3650 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003651 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3652 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003653 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003654 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003655 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003656 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003657 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003658 (void)Success; assert(Success && "Couldn't select *anything*?");
3659
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003660 // The match was to check the profitability, the changes made are not
3661 // part of the original matcher. Therefore, they should be dropped
3662 // otherwise the original matcher will not present the right state.
3663 TPT.rollback(LastKnownGood);
3664
Chandler Carruthc8925912013-01-05 02:09:22 +00003665 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003666 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003667 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003668
Chandler Carruthc8925912013-01-05 02:09:22 +00003669 MatchedAddrModeInsts.clear();
3670 }
Stephen Lin837bba12013-07-15 17:55:02 +00003671
Chandler Carruthc8925912013-01-05 02:09:22 +00003672 return true;
3673}
3674
3675} // end anonymous namespace
3676
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003677/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003678/// different basic block than BB.
3679static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3680 if (Instruction *I = dyn_cast<Instruction>(V))
3681 return I->getParent() != BB;
3682 return false;
3683}
3684
Philip Reamesac115ed2016-03-09 23:13:12 +00003685/// Sink addressing mode computation immediate before MemoryInst if doing so
3686/// can be done without increasing register pressure. The need for the
3687/// register pressure constraint means this can end up being an all or nothing
3688/// decision for all uses of the same addressing computation.
3689///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003690/// Load and Store Instructions often have addressing modes that can do
3691/// significant amounts of computation. As such, instruction selection will try
3692/// to get the load or store to do as much computation as possible for the
3693/// program. The problem is that isel can only see within a single block. As
3694/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003695///
3696/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003697/// operands. It's also used to sink addressing computations feeding into cold
3698/// call sites into their (cold) basic block.
3699///
3700/// The motivation for handling sinking into cold blocks is that doing so can
3701/// both enable other address mode sinking (by satisfying the register pressure
3702/// constraint above), and reduce register pressure globally (by removing the
3703/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003704bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003705 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003706 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003707
3708 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003709 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003710 SmallVector<Value*, 8> worklist;
3711 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003712 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003713
Owen Anderson8ba5f392010-11-27 08:15:55 +00003714 // Use a worklist to iteratively look through PHI nodes, and ensure that
3715 // the addressing mode obtained from the non-PHI roots of the graph
3716 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003717 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003718 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003719 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003720 SmallVector<Instruction*, 16> AddrModeInsts;
3721 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003722 TypePromotionTransaction TPT;
3723 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3724 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003725 while (!worklist.empty()) {
3726 Value *V = worklist.back();
3727 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003728
Owen Anderson8ba5f392010-11-27 08:15:55 +00003729 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003730 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003731 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003732 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003733 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003734
Owen Anderson8ba5f392010-11-27 08:15:55 +00003735 // For a PHI node, push all of its incoming values.
3736 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003737 for (Value *IncValue : P->incoming_values())
3738 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003739 continue;
3740 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003741
Philip Reamesac115ed2016-03-09 23:13:12 +00003742 // For non-PHIs, determine the addressing mode being computed. Note that
3743 // the result may differ depending on what other uses our candidate
3744 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003745 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003746 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003747 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003748 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003749
3750 // This check is broken into two cases with very similar code to avoid using
3751 // getNumUses() as much as possible. Some values have a lot of uses, so
3752 // calling getNumUses() unconditionally caused a significant compile-time
3753 // regression.
3754 if (!Consensus) {
3755 Consensus = V;
3756 AddrMode = NewAddrMode;
3757 AddrModeInsts = NewAddrModeInsts;
3758 continue;
3759 } else if (NewAddrMode == AddrMode) {
3760 if (!IsNumUsesConsensusValid) {
3761 NumUsesConsensus = Consensus->getNumUses();
3762 IsNumUsesConsensusValid = true;
3763 }
3764
3765 // Ensure that the obtained addressing mode is equivalent to that obtained
3766 // for all other roots of the PHI traversal. Also, when choosing one
3767 // such root as representative, select the one with the most uses in order
3768 // to keep the cost modeling heuristics in AddressingModeMatcher
3769 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003770 unsigned NumUses = V->getNumUses();
3771 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003772 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003773 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003774 AddrModeInsts = NewAddrModeInsts;
3775 }
3776 continue;
3777 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003778
Craig Topperc0196b12014-04-14 00:51:57 +00003779 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003780 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003781 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003782
Owen Anderson8ba5f392010-11-27 08:15:55 +00003783 // If the addressing mode couldn't be determined, or if multiple different
3784 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003785 if (!Consensus) {
3786 TPT.rollback(LastKnownGood);
3787 return false;
3788 }
3789 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003790
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003791 // Check to see if any of the instructions supersumed by this addr mode are
3792 // non-local to I's BB.
3793 bool AnyNonLocal = false;
3794 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003795 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003796 AnyNonLocal = true;
3797 break;
3798 }
3799 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003800
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003801 // If all the instructions matched are already in this BB, don't do anything.
3802 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003803 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003804 return false;
3805 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003806
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003807 // Insert this computation right after this user. Since our caller is
3808 // scanning from the top of the BB to the bottom, reuse of the expr are
3809 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003810 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003811
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003812 // Now that we determined the addressing expression we want to use and know
3813 // that we have to sink it into this block. Check to see if we have already
3814 // done this for some other load/store instr in this block. If so, reuse the
3815 // computation.
3816 Value *&SunkAddr = SunkAddrs[Addr];
3817 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003818 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003819 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003820 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003821 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003822 } else if (AddrSinkUsingGEPs ||
3823 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003824 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3825 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003826 // By default, we use the GEP-based method when AA is used later. This
3827 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3828 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003829 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003830 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003831 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003832
3833 // First, find the pointer.
3834 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3835 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003836 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003837 }
3838
3839 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3840 // We can't add more than one pointer together, nor can we scale a
3841 // pointer (both of which seem meaningless).
3842 if (ResultPtr || AddrMode.Scale != 1)
3843 return false;
3844
3845 ResultPtr = AddrMode.ScaledReg;
3846 AddrMode.Scale = 0;
3847 }
3848
3849 if (AddrMode.BaseGV) {
3850 if (ResultPtr)
3851 return false;
3852
3853 ResultPtr = AddrMode.BaseGV;
3854 }
3855
3856 // If the real base value actually came from an inttoptr, then the matcher
3857 // will look through it and provide only the integer value. In that case,
3858 // use it here.
3859 if (!ResultPtr && AddrMode.BaseReg) {
3860 ResultPtr =
3861 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003862 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003863 } else if (!ResultPtr && AddrMode.Scale == 1) {
3864 ResultPtr =
3865 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3866 AddrMode.Scale = 0;
3867 }
3868
3869 if (!ResultPtr &&
3870 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3871 SunkAddr = Constant::getNullValue(Addr->getType());
3872 } else if (!ResultPtr) {
3873 return false;
3874 } else {
3875 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003876 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3877 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003878
3879 // Start with the base register. Do this first so that subsequent address
3880 // matching finds it last, which will prevent it from trying to match it
3881 // as the scaled value in case it happens to be a mul. That would be
3882 // problematic if we've sunk a different mul for the scale, because then
3883 // we'd end up sinking both muls.
3884 if (AddrMode.BaseReg) {
3885 Value *V = AddrMode.BaseReg;
3886 if (V->getType() != IntPtrTy)
3887 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3888
3889 ResultIndex = V;
3890 }
3891
3892 // Add the scale value.
3893 if (AddrMode.Scale) {
3894 Value *V = AddrMode.ScaledReg;
3895 if (V->getType() == IntPtrTy) {
3896 // done.
3897 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3898 cast<IntegerType>(V->getType())->getBitWidth()) {
3899 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3900 } else {
3901 // It is only safe to sign extend the BaseReg if we know that the math
3902 // required to create it did not overflow before we extend it. Since
3903 // the original IR value was tossed in favor of a constant back when
3904 // the AddrMode was created we need to bail out gracefully if widths
3905 // do not match instead of extending it.
3906 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3907 if (I && (ResultIndex != AddrMode.BaseReg))
3908 I->eraseFromParent();
3909 return false;
3910 }
3911
3912 if (AddrMode.Scale != 1)
3913 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3914 "sunkaddr");
3915 if (ResultIndex)
3916 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3917 else
3918 ResultIndex = V;
3919 }
3920
3921 // Add in the Base Offset if present.
3922 if (AddrMode.BaseOffs) {
3923 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3924 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003925 // We need to add this separately from the scale above to help with
3926 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003927 if (ResultPtr->getType() != I8PtrTy)
3928 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003929 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003930 }
3931
3932 ResultIndex = V;
3933 }
3934
3935 if (!ResultIndex) {
3936 SunkAddr = ResultPtr;
3937 } else {
3938 if (ResultPtr->getType() != I8PtrTy)
3939 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003940 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003941 }
3942
3943 if (SunkAddr->getType() != Addr->getType())
3944 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3945 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003946 } else {
David Greene74e2d492010-01-05 01:27:11 +00003947 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003948 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003949 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003950 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003951
3952 // Start with the base register. Do this first so that subsequent address
3953 // matching finds it last, which will prevent it from trying to match it
3954 // as the scaled value in case it happens to be a mul. That would be
3955 // problematic if we've sunk a different mul for the scale, because then
3956 // we'd end up sinking both muls.
3957 if (AddrMode.BaseReg) {
3958 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003959 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003960 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003961 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003962 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003963 Result = V;
3964 }
3965
3966 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003967 if (AddrMode.Scale) {
3968 Value *V = AddrMode.ScaledReg;
3969 if (V->getType() == IntPtrTy) {
3970 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003971 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003972 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003973 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3974 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003975 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003976 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003977 // It is only safe to sign extend the BaseReg if we know that the math
3978 // required to create it did not overflow before we extend it. Since
3979 // the original IR value was tossed in favor of a constant back when
3980 // the AddrMode was created we need to bail out gracefully if widths
3981 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003982 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003983 if (I && (Result != AddrMode.BaseReg))
3984 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003985 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003986 }
3987 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003988 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3989 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003990 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003991 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003992 else
3993 Result = V;
3994 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003995
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003996 // Add in the BaseGV if present.
3997 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003998 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003999 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004000 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004001 else
4002 Result = V;
4003 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004004
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004005 // Add in the Base Offset if present.
4006 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004007 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
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 }
4013
Craig Topperc0196b12014-04-14 00:51:57 +00004014 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004015 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004016 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004017 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004018 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004019
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004020 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004021
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004022 // If we have no uses, recursively delete the value and all dead instructions
4023 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004024 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004025 // This can cause recursive deletion, which can invalidate our iterator.
4026 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004027 Value *CurValue = &*CurInstIterator;
4028 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004029 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004030
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004031 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004032
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004033 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004034 // If the iterator instruction was recursively deleted, start over at the
4035 // start of the block.
4036 CurInstIterator = BB->begin();
4037 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004038 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004039 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004040 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004041 return true;
4042}
4043
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004044/// If there are any memory operands, use OptimizeMemoryInst to sink their
4045/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004046bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004047 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004048
Eric Christopher11e4df72015-02-26 22:38:43 +00004049 const TargetRegisterInfo *TRI =
4050 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004051 TargetLowering::AsmOperandInfoVector TargetConstraints =
4052 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004053 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004054 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4055 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004056
Evan Cheng1da25002008-02-26 02:42:37 +00004057 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004058 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004059
Eli Friedman666bbe32008-02-26 18:37:49 +00004060 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4061 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004062 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004063 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004064 } else if (OpInfo.Type == InlineAsm::isInput)
4065 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004066 }
4067
4068 return MadeChange;
4069}
4070
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004071/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4072/// sign extensions.
4073static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4074 assert(!Inst->use_empty() && "Input must have at least one use");
4075 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4076 bool IsSExt = isa<SExtInst>(FirstUser);
4077 Type *ExtTy = FirstUser->getType();
4078 for (const User *U : Inst->users()) {
4079 const Instruction *UI = cast<Instruction>(U);
4080 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4081 return false;
4082 Type *CurTy = UI->getType();
4083 // Same input and output types: Same instruction after CSE.
4084 if (CurTy == ExtTy)
4085 continue;
4086
4087 // If IsSExt is true, we are in this situation:
4088 // a = Inst
4089 // b = sext ty1 a to ty2
4090 // c = sext ty1 a to ty3
4091 // Assuming ty2 is shorter than ty3, this could be turned into:
4092 // a = Inst
4093 // b = sext ty1 a to ty2
4094 // c = sext ty2 b to ty3
4095 // However, the last sext is not free.
4096 if (IsSExt)
4097 return false;
4098
4099 // This is a ZExt, maybe this is free to extend from one type to another.
4100 // In that case, we would not account for a different use.
4101 Type *NarrowTy;
4102 Type *LargeTy;
4103 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4104 CurTy->getScalarType()->getIntegerBitWidth()) {
4105 NarrowTy = CurTy;
4106 LargeTy = ExtTy;
4107 } else {
4108 NarrowTy = ExtTy;
4109 LargeTy = CurTy;
4110 }
4111
4112 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4113 return false;
4114 }
4115 // All uses are the same or can be derived from one another for free.
4116 return true;
4117}
4118
4119/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4120/// load instruction.
4121/// If an ext(load) can be formed, it is returned via \p LI for the load
4122/// and \p Inst for the extension.
4123/// Otherwise LI == nullptr and Inst == nullptr.
4124/// When some promotion happened, \p TPT contains the proper state to
4125/// revert them.
4126///
4127/// \return true when promoting was necessary to expose the ext(load)
4128/// opportunity, false otherwise.
4129///
4130/// Example:
4131/// \code
4132/// %ld = load i32* %addr
4133/// %add = add nuw i32 %ld, 4
4134/// %zext = zext i32 %add to i64
4135/// \endcode
4136/// =>
4137/// \code
4138/// %ld = load i32* %addr
4139/// %zext = zext i32 %ld to i64
4140/// %add = add nuw i64 %zext, 4
4141/// \encode
4142/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004143bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004144 LoadInst *&LI, Instruction *&Inst,
4145 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004146 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004147 // Iterate over all the extensions to see if one form an ext(load).
4148 for (auto I : Exts) {
4149 // Check if we directly have ext(load).
4150 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4151 Inst = I;
4152 // No promotion happened here.
4153 return false;
4154 }
4155 // Check whether or not we want to do any promotion.
4156 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4157 continue;
4158 // Get the action to perform the promotion.
4159 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004160 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004161 // Check if we can promote.
4162 if (!TPH)
4163 continue;
4164 // Save the current state.
4165 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4166 TPT.getRestorationPoint();
4167 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004168 unsigned NewCreatedInstsCost = 0;
4169 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004170 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004171 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4172 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004173 assert(PromotedVal &&
4174 "TypePromotionHelper should have filtered out those cases");
4175
4176 // We would be able to merge only one extension in a load.
4177 // Therefore, if we have more than 1 new extension we heuristically
4178 // cut this search path, because it means we degrade the code quality.
4179 // With exactly 2, the transformation is neutral, because we will merge
4180 // one extension but leave one. However, we optimistically keep going,
4181 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004182 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4183 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004184 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004185 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004186 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004187 // The promotion is not profitable, rollback to the previous state.
4188 TPT.rollback(LastKnownGood);
4189 continue;
4190 }
4191 // The promotion is profitable.
4192 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004193 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004194 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004195 // If we have created a new extension, i.e., now we have two
4196 // extensions. We must make sure one of them is merged with
4197 // the load, otherwise we may degrade the code quality.
4198 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4199 // Promotion happened.
4200 return true;
4201 // If this does not help to expose an ext(load) then, rollback.
4202 TPT.rollback(LastKnownGood);
4203 }
4204 // None of the extension can form an ext(load).
4205 LI = nullptr;
4206 Inst = nullptr;
4207 return false;
4208}
4209
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004210/// Move a zext or sext fed by a load into the same basic block as the load,
4211/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4212/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004213/// \p I[in/out] the extension may be modified during the process if some
4214/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004215///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004216bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004217 // Try to promote a chain of computation if it allows to form
4218 // an extended load.
4219 TypePromotionTransaction TPT;
4220 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4221 TPT.getRestorationPoint();
4222 SmallVector<Instruction *, 1> Exts;
4223 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004224 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004225 LoadInst *LI = nullptr;
4226 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004227 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004228 if (!LI || !I) {
4229 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4230 "the code must remain the same");
4231 I = OldExt;
4232 return false;
4233 }
Dan Gohman99429a02009-10-16 20:59:35 +00004234
4235 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004236 // Make the cheap checks first if we did not promote.
4237 // If we promoted, we need to check if it is indeed profitable.
4238 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004239 return false;
4240
Mehdi Amini44ede332015-07-09 02:09:04 +00004241 EVT VT = TLI->getValueType(*DL, I->getType());
4242 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004243
Dan Gohman99429a02009-10-16 20:59:35 +00004244 // If the load has other users and the truncate is not free, this probably
4245 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004246 if (!LI->hasOneUse() && TLI &&
4247 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004248 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4249 I = OldExt;
4250 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004251 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004252 }
Dan Gohman99429a02009-10-16 20:59:35 +00004253
4254 // Check whether the target supports casts folded into loads.
4255 unsigned LType;
4256 if (isa<ZExtInst>(I))
4257 LType = ISD::ZEXTLOAD;
4258 else {
4259 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4260 LType = ISD::SEXTLOAD;
4261 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004262 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004263 I = OldExt;
4264 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004265 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004266 }
Dan Gohman99429a02009-10-16 20:59:35 +00004267
4268 // Move the extend into the same block as the load, so that SelectionDAG
4269 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004270 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004271 I->removeFromParent();
4272 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004273 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004274 return true;
4275}
4276
Sanjay Patelfc580a62015-09-21 23:03:16 +00004277bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004278 BasicBlock *DefBB = I->getParent();
4279
Bob Wilsonff714f92010-09-21 21:44:14 +00004280 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004281 // other uses of the source with result of extension.
4282 Value *Src = I->getOperand(0);
4283 if (Src->hasOneUse())
4284 return false;
4285
Evan Cheng2011df42007-12-13 07:50:36 +00004286 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004287 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004288 return false;
4289
Evan Cheng7bc89422007-12-12 00:51:06 +00004290 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004291 // this block.
4292 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004293 return false;
4294
Evan Chengd3d80172007-12-05 23:58:20 +00004295 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004296 for (User *U : I->users()) {
4297 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004298
4299 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004300 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004301 if (UserBB == DefBB) continue;
4302 DefIsLiveOut = true;
4303 break;
4304 }
4305 if (!DefIsLiveOut)
4306 return false;
4307
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004308 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004309 for (User *U : Src->users()) {
4310 Instruction *UI = cast<Instruction>(U);
4311 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004312 if (UserBB == DefBB) continue;
4313 // Be conservative. We don't want this xform to end up introducing
4314 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004315 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004316 return false;
4317 }
4318
Evan Chengd3d80172007-12-05 23:58:20 +00004319 // InsertedTruncs - Only insert one trunc in each block once.
4320 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4321
4322 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004323 for (Use &U : Src->uses()) {
4324 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004325
4326 // Figure out which BB this ext is used in.
4327 BasicBlock *UserBB = User->getParent();
4328 if (UserBB == DefBB) continue;
4329
4330 // Both src and def are live in this block. Rewrite the use.
4331 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4332
4333 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004334 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004335 assert(InsertPt != UserBB->end());
4336 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004337 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004338 }
4339
4340 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004341 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004342 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004343 MadeChange = true;
4344 }
4345
4346 return MadeChange;
4347}
4348
Geoff Berry5256fca2015-11-20 22:34:39 +00004349// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4350// just after the load if the target can fold this into one extload instruction,
4351// with the hope of eliminating some of the other later "and" instructions using
4352// the loaded value. "and"s that are made trivially redundant by the insertion
4353// of the new "and" are removed by this function, while others (e.g. those whose
4354// path from the load goes through a phi) are left for isel to potentially
4355// remove.
4356//
4357// For example:
4358//
4359// b0:
4360// x = load i32
4361// ...
4362// b1:
4363// y = and x, 0xff
4364// z = use y
4365//
4366// becomes:
4367//
4368// b0:
4369// x = load i32
4370// x' = and x, 0xff
4371// ...
4372// b1:
4373// z = use x'
4374//
4375// whereas:
4376//
4377// b0:
4378// x1 = load i32
4379// ...
4380// b1:
4381// x2 = load i32
4382// ...
4383// b2:
4384// x = phi x1, x2
4385// y = and x, 0xff
4386//
4387// becomes (after a call to optimizeLoadExt for each load):
4388//
4389// b0:
4390// x1 = load i32
4391// x1' = and x1, 0xff
4392// ...
4393// b1:
4394// x2 = load i32
4395// x2' = and x2, 0xff
4396// ...
4397// b2:
4398// x = phi x1', x2'
4399// y = and x, 0xff
4400//
4401
4402bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4403
4404 if (!Load->isSimple() ||
4405 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4406 return false;
4407
4408 // Skip loads we've already transformed or have no reason to transform.
4409 if (Load->hasOneUse()) {
4410 User *LoadUser = *Load->user_begin();
4411 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4412 !dyn_cast<PHINode>(LoadUser))
4413 return false;
4414 }
4415
4416 // Look at all uses of Load, looking through phis, to determine how many bits
4417 // of the loaded value are needed.
4418 SmallVector<Instruction *, 8> WorkList;
4419 SmallPtrSet<Instruction *, 16> Visited;
4420 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4421 for (auto *U : Load->users())
4422 WorkList.push_back(cast<Instruction>(U));
4423
4424 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4425 unsigned BitWidth = LoadResultVT.getSizeInBits();
4426 APInt DemandBits(BitWidth, 0);
4427 APInt WidestAndBits(BitWidth, 0);
4428
4429 while (!WorkList.empty()) {
4430 Instruction *I = WorkList.back();
4431 WorkList.pop_back();
4432
4433 // Break use-def graph loops.
4434 if (!Visited.insert(I).second)
4435 continue;
4436
4437 // For a PHI node, push all of its users.
4438 if (auto *Phi = dyn_cast<PHINode>(I)) {
4439 for (auto *U : Phi->users())
4440 WorkList.push_back(cast<Instruction>(U));
4441 continue;
4442 }
4443
4444 switch (I->getOpcode()) {
4445 case llvm::Instruction::And: {
4446 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4447 if (!AndC)
4448 return false;
4449 APInt AndBits = AndC->getValue();
4450 DemandBits |= AndBits;
4451 // Keep track of the widest and mask we see.
4452 if (AndBits.ugt(WidestAndBits))
4453 WidestAndBits = AndBits;
4454 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4455 AndsToMaybeRemove.push_back(I);
4456 break;
4457 }
4458
4459 case llvm::Instruction::Shl: {
4460 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4461 if (!ShlC)
4462 return false;
4463 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4464 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4465 DemandBits |= ShlDemandBits;
4466 break;
4467 }
4468
4469 case llvm::Instruction::Trunc: {
4470 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4471 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4472 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4473 DemandBits |= TruncBits;
4474 break;
4475 }
4476
4477 default:
4478 return false;
4479 }
4480 }
4481
4482 uint32_t ActiveBits = DemandBits.getActiveBits();
4483 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4484 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4485 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4486 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4487 // followed by an AND.
4488 // TODO: Look into removing this restriction by fixing backends to either
4489 // return false for isLoadExtLegal for i1 or have them select this pattern to
4490 // a single instruction.
4491 //
4492 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4493 // mask, since these are the only ands that will be removed by isel.
4494 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4495 WidestAndBits != DemandBits)
4496 return false;
4497
4498 LLVMContext &Ctx = Load->getType()->getContext();
4499 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4500 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4501
4502 // Reject cases that won't be matched as extloads.
4503 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4504 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4505 return false;
4506
4507 IRBuilder<> Builder(Load->getNextNode());
4508 auto *NewAnd = dyn_cast<Instruction>(
4509 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4510
4511 // Replace all uses of load with new and (except for the use of load in the
4512 // new and itself).
4513 Load->replaceAllUsesWith(NewAnd);
4514 NewAnd->setOperand(0, Load);
4515
4516 // Remove any and instructions that are now redundant.
4517 for (auto *And : AndsToMaybeRemove)
4518 // Check that the and mask is the same as the one we decided to put on the
4519 // new and.
4520 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4521 And->replaceAllUsesWith(NewAnd);
4522 if (&*CurInstIterator == And)
4523 CurInstIterator = std::next(And->getIterator());
4524 And->eraseFromParent();
4525 ++NumAndUses;
4526 }
4527
4528 ++NumAndsAdded;
4529 return true;
4530}
4531
Sanjay Patel69a50a12015-10-19 21:59:12 +00004532/// Check if V (an operand of a select instruction) is an expensive instruction
4533/// that is only used once.
4534static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4535 auto *I = dyn_cast<Instruction>(V);
4536 // If it's safe to speculatively execute, then it should not have side
4537 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004538 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4539 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004540}
4541
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004542/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004543static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004544 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004545 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004546 // If even a predictable select is cheap, then a branch can't be cheaper.
4547 if (!TLI->isPredictableSelectExpensive())
4548 return false;
4549
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004550 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004551 // whether a select is better represented as a branch.
4552
4553 // If metadata tells us that the select condition is obviously predictable,
4554 // then we want to replace the select with a branch.
4555 uint64_t TrueWeight, FalseWeight;
4556 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4557 uint64_t Max = std::max(TrueWeight, FalseWeight);
4558 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004559 if (Sum != 0) {
4560 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4561 if (Probability > TLI->getPredictableBranchThreshold())
4562 return true;
4563 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004564 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004565
4566 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4567
Sanjay Patel4e652762015-09-28 22:14:51 +00004568 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4569 // comparison condition. If the compare has more than one use, there's
4570 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004571 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004572 return false;
4573
Sanjay Patel69a50a12015-10-19 21:59:12 +00004574 // If either operand of the select is expensive and only needed on one side
4575 // of the select, we should form a branch.
4576 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4577 sinkSelectOperand(TTI, SI->getFalseValue()))
4578 return true;
4579
4580 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004581}
4582
Dehao Chen9bbb9412016-09-12 20:23:28 +00004583/// If \p isTrue is true, return the true value of \p SI, otherwise return
4584/// false value of \p SI. If the true/false value of \p SI is defined by any
4585/// select instructions in \p Selects, look through the defining select
4586/// instruction until the true/false value is not defined in \p Selects.
4587static Value *getTrueOrFalseValue(
4588 SelectInst *SI, bool isTrue,
4589 const SmallPtrSet<const Instruction *, 2> &Selects) {
4590 Value *V;
4591
4592 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4593 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004594 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004595 "The condition of DefSI does not match with SI");
4596 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4597 }
4598 return V;
4599}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004600
Nadav Rotem9d832022012-09-02 12:10:19 +00004601/// If we have a SelectInst that will likely profit from branch prediction,
4602/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004603bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004604 // Find all consecutive select instructions that share the same condition.
4605 SmallVector<SelectInst *, 2> ASI;
4606 ASI.push_back(SI);
4607 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4608 It != SI->getParent()->end(); ++It) {
4609 SelectInst *I = dyn_cast<SelectInst>(&*It);
4610 if (I && SI->getCondition() == I->getCondition()) {
4611 ASI.push_back(I);
4612 } else {
4613 break;
4614 }
4615 }
4616
4617 SelectInst *LastSI = ASI.back();
4618 // Increment the current iterator to skip all the rest of select instructions
4619 // because they will be either "not lowered" or "all lowered" to branch.
4620 CurInstIterator = std::next(LastSI->getIterator());
4621
Nadav Rotem9d832022012-09-02 12:10:19 +00004622 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4623
4624 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004625 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4626 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004627 return false;
4628
Nadav Rotem9d832022012-09-02 12:10:19 +00004629 TargetLowering::SelectSupportKind SelectKind;
4630 if (VectorCond)
4631 SelectKind = TargetLowering::VectorMaskSelect;
4632 else if (SI->getType()->isVectorTy())
4633 SelectKind = TargetLowering::ScalarCondVectorVal;
4634 else
4635 SelectKind = TargetLowering::ScalarValSelect;
4636
Sanjay Pateld66607b2016-04-26 17:11:17 +00004637 if (TLI->isSelectSupported(SelectKind) &&
4638 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4639 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004640
4641 ModifiedDT = true;
4642
Sanjay Patel69a50a12015-10-19 21:59:12 +00004643 // Transform a sequence like this:
4644 // start:
4645 // %cmp = cmp uge i32 %a, %b
4646 // %sel = select i1 %cmp, i32 %c, i32 %d
4647 //
4648 // Into:
4649 // start:
4650 // %cmp = cmp uge i32 %a, %b
4651 // br i1 %cmp, label %select.true, label %select.false
4652 // select.true:
4653 // br label %select.end
4654 // select.false:
4655 // br label %select.end
4656 // select.end:
4657 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4658 //
4659 // In addition, we may sink instructions that produce %c or %d from
4660 // the entry block into the destination(s) of the new branch.
4661 // If the true or false blocks do not contain a sunken instruction, that
4662 // block and its branch may be optimized away. In that case, one side of the
4663 // first branch will point directly to select.end, and the corresponding PHI
4664 // predecessor block will be the start block.
4665
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004666 // First, we split the block containing the select into 2 blocks.
4667 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004668 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004669 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004670
Sanjay Patel69a50a12015-10-19 21:59:12 +00004671 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004672 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004673
4674 // These are the new basic blocks for the conditional branch.
4675 // At least one will become an actual new basic block.
4676 BasicBlock *TrueBlock = nullptr;
4677 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004678 BranchInst *TrueBranch = nullptr;
4679 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004680
4681 // Sink expensive instructions into the conditional blocks to avoid executing
4682 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004683 for (SelectInst *SI : ASI) {
4684 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4685 if (TrueBlock == nullptr) {
4686 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4687 EndBlock->getParent(), EndBlock);
4688 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4689 }
4690 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4691 TrueInst->moveBefore(TrueBranch);
4692 }
4693 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4694 if (FalseBlock == nullptr) {
4695 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4696 EndBlock->getParent(), EndBlock);
4697 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4698 }
4699 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4700 FalseInst->moveBefore(FalseBranch);
4701 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004702 }
4703
4704 // If there was nothing to sink, then arbitrarily choose the 'false' side
4705 // for a new input value to the PHI.
4706 if (TrueBlock == FalseBlock) {
4707 assert(TrueBlock == nullptr &&
4708 "Unexpected basic block transform while optimizing select");
4709
4710 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4711 EndBlock->getParent(), EndBlock);
4712 BranchInst::Create(EndBlock, FalseBlock);
4713 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004714
4715 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004716 // If we did not create a new block for one of the 'true' or 'false' paths
4717 // of the condition, it means that side of the branch goes to the end block
4718 // directly and the path originates from the start block from the point of
4719 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004720 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004721 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004722 TT = EndBlock;
4723 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004724 TrueBlock = StartBlock;
4725 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004726 TT = TrueBlock;
4727 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004728 FalseBlock = StartBlock;
4729 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004730 TT = TrueBlock;
4731 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004732 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004733 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004734
Dehao Chen9bbb9412016-09-12 20:23:28 +00004735 SmallPtrSet<const Instruction *, 2> INS;
4736 INS.insert(ASI.begin(), ASI.end());
4737 // Use reverse iterator because later select may use the value of the
4738 // earlier select, and we need to propagate value through earlier select
4739 // to get the PHI operand.
4740 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4741 SelectInst *SI = *It;
4742 // The select itself is replaced with a PHI Node.
4743 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4744 PN->takeName(SI);
4745 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4746 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004747
Dehao Chen9bbb9412016-09-12 20:23:28 +00004748 SI->replaceAllUsesWith(PN);
4749 SI->eraseFromParent();
4750 INS.erase(SI);
4751 ++NumSelectsExpanded;
4752 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004753
4754 // Instruct OptimizeBlock to skip to the next block.
4755 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004756 return true;
4757}
4758
Benjamin Kramer573ff362014-03-01 17:24:40 +00004759static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004760 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4761 int SplatElem = -1;
4762 for (unsigned i = 0; i < Mask.size(); ++i) {
4763 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4764 return false;
4765 SplatElem = Mask[i];
4766 }
4767
4768 return true;
4769}
4770
4771/// Some targets have expensive vector shifts if the lanes aren't all the same
4772/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4773/// it's often worth sinking a shufflevector splat down to its use so that
4774/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004775bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004776 BasicBlock *DefBB = SVI->getParent();
4777
4778 // Only do this xform if variable vector shifts are particularly expensive.
4779 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4780 return false;
4781
4782 // We only expect better codegen by sinking a shuffle if we can recognise a
4783 // constant splat.
4784 if (!isBroadcastShuffle(SVI))
4785 return false;
4786
4787 // InsertedShuffles - Only insert a shuffle in each block once.
4788 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4789
4790 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004791 for (User *U : SVI->users()) {
4792 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004793
4794 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004795 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004796 if (UserBB == DefBB) continue;
4797
4798 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004799 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004800
4801 // Everything checks out, sink the shuffle if the user's block doesn't
4802 // already have a copy.
4803 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4804
4805 if (!InsertedShuffle) {
4806 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004807 assert(InsertPt != UserBB->end());
4808 InsertedShuffle =
4809 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4810 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004811 }
4812
Chandler Carruthcdf47882014-03-09 03:16:01 +00004813 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004814 MadeChange = true;
4815 }
4816
4817 // If we removed all uses, nuke the shuffle.
4818 if (SVI->use_empty()) {
4819 SVI->eraseFromParent();
4820 MadeChange = true;
4821 }
4822
4823 return MadeChange;
4824}
4825
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004826bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4827 if (!TLI || !DL)
4828 return false;
4829
4830 Value *Cond = SI->getCondition();
4831 Type *OldType = Cond->getType();
4832 LLVMContext &Context = Cond->getContext();
4833 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4834 unsigned RegWidth = RegType.getSizeInBits();
4835
4836 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4837 return false;
4838
4839 // If the register width is greater than the type width, expand the condition
4840 // of the switch instruction and each case constant to the width of the
4841 // register. By widening the type of the switch condition, subsequent
4842 // comparisons (for case comparisons) will not need to be extended to the
4843 // preferred register width, so we will potentially eliminate N-1 extends,
4844 // where N is the number of cases in the switch.
4845 auto *NewType = Type::getIntNTy(Context, RegWidth);
4846
4847 // Zero-extend the switch condition and case constants unless the switch
4848 // condition is a function argument that is already being sign-extended.
4849 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4850 // everything instead.
4851 Instruction::CastOps ExtType = Instruction::ZExt;
4852 if (auto *Arg = dyn_cast<Argument>(Cond))
4853 if (Arg->hasSExtAttr())
4854 ExtType = Instruction::SExt;
4855
4856 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4857 ExtInst->insertBefore(SI);
4858 SI->setCondition(ExtInst);
4859 for (SwitchInst::CaseIt Case : SI->cases()) {
4860 APInt NarrowConst = Case.getCaseValue()->getValue();
4861 APInt WideConst = (ExtType == Instruction::ZExt) ?
4862 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4863 Case.setValue(ConstantInt::get(Context, WideConst));
4864 }
4865
4866 return true;
4867}
4868
Quentin Colombetc32615d2014-10-31 17:52:53 +00004869namespace {
4870/// \brief Helper class to promote a scalar operation to a vector one.
4871/// This class is used to move downward extractelement transition.
4872/// E.g.,
4873/// a = vector_op <2 x i32>
4874/// b = extractelement <2 x i32> a, i32 0
4875/// c = scalar_op b
4876/// store c
4877///
4878/// =>
4879/// a = vector_op <2 x i32>
4880/// c = vector_op a (equivalent to scalar_op on the related lane)
4881/// * d = extractelement <2 x i32> c, i32 0
4882/// * store d
4883/// Assuming both extractelement and store can be combine, we get rid of the
4884/// transition.
4885class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004886 /// DataLayout associated with the current module.
4887 const DataLayout &DL;
4888
Quentin Colombetc32615d2014-10-31 17:52:53 +00004889 /// Used to perform some checks on the legality of vector operations.
4890 const TargetLowering &TLI;
4891
4892 /// Used to estimated the cost of the promoted chain.
4893 const TargetTransformInfo &TTI;
4894
4895 /// The transition being moved downwards.
4896 Instruction *Transition;
4897 /// The sequence of instructions to be promoted.
4898 SmallVector<Instruction *, 4> InstsToBePromoted;
4899 /// Cost of combining a store and an extract.
4900 unsigned StoreExtractCombineCost;
4901 /// Instruction that will be combined with the transition.
4902 Instruction *CombineInst;
4903
4904 /// \brief The instruction that represents the current end of the transition.
4905 /// Since we are faking the promotion until we reach the end of the chain
4906 /// of computation, we need a way to get the current end of the transition.
4907 Instruction *getEndOfTransition() const {
4908 if (InstsToBePromoted.empty())
4909 return Transition;
4910 return InstsToBePromoted.back();
4911 }
4912
4913 /// \brief Return the index of the original value in the transition.
4914 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4915 /// c, is at index 0.
4916 unsigned getTransitionOriginalValueIdx() const {
4917 assert(isa<ExtractElementInst>(Transition) &&
4918 "Other kind of transitions are not supported yet");
4919 return 0;
4920 }
4921
4922 /// \brief Return the index of the index in the transition.
4923 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4924 /// is at index 1.
4925 unsigned getTransitionIdx() const {
4926 assert(isa<ExtractElementInst>(Transition) &&
4927 "Other kind of transitions are not supported yet");
4928 return 1;
4929 }
4930
4931 /// \brief Get the type of the transition.
4932 /// This is the type of the original value.
4933 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4934 /// transition is <2 x i32>.
4935 Type *getTransitionType() const {
4936 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4937 }
4938
4939 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4940 /// I.e., we have the following sequence:
4941 /// Def = Transition <ty1> a to <ty2>
4942 /// b = ToBePromoted <ty2> Def, ...
4943 /// =>
4944 /// b = ToBePromoted <ty1> a, ...
4945 /// Def = Transition <ty1> ToBePromoted to <ty2>
4946 void promoteImpl(Instruction *ToBePromoted);
4947
4948 /// \brief Check whether or not it is profitable to promote all the
4949 /// instructions enqueued to be promoted.
4950 bool isProfitableToPromote() {
4951 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4952 unsigned Index = isa<ConstantInt>(ValIdx)
4953 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4954 : -1;
4955 Type *PromotedType = getTransitionType();
4956
4957 StoreInst *ST = cast<StoreInst>(CombineInst);
4958 unsigned AS = ST->getPointerAddressSpace();
4959 unsigned Align = ST->getAlignment();
4960 // Check if this store is supported.
4961 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004962 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4963 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004964 // If this is not supported, there is no way we can combine
4965 // the extract with the store.
4966 return false;
4967 }
4968
4969 // The scalar chain of computation has to pay for the transition
4970 // scalar to vector.
4971 // The vector chain has to account for the combining cost.
4972 uint64_t ScalarCost =
4973 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4974 uint64_t VectorCost = StoreExtractCombineCost;
4975 for (const auto &Inst : InstsToBePromoted) {
4976 // Compute the cost.
4977 // By construction, all instructions being promoted are arithmetic ones.
4978 // Moreover, one argument is a constant that can be viewed as a splat
4979 // constant.
4980 Value *Arg0 = Inst->getOperand(0);
4981 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4982 isa<ConstantFP>(Arg0);
4983 TargetTransformInfo::OperandValueKind Arg0OVK =
4984 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4985 : TargetTransformInfo::OK_AnyValue;
4986 TargetTransformInfo::OperandValueKind Arg1OVK =
4987 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4988 : TargetTransformInfo::OK_AnyValue;
4989 ScalarCost += TTI.getArithmeticInstrCost(
4990 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4991 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4992 Arg0OVK, Arg1OVK);
4993 }
4994 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4995 << ScalarCost << "\nVector: " << VectorCost << '\n');
4996 return ScalarCost > VectorCost;
4997 }
4998
4999 /// \brief Generate a constant vector with \p Val with the same
5000 /// number of elements as the transition.
5001 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005002 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005003 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5004 /// otherwise we generate a vector with as many undef as possible:
5005 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5006 /// used at the index of the extract.
5007 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5008 unsigned ExtractIdx = UINT_MAX;
5009 if (!UseSplat) {
5010 // If we cannot determine where the constant must be, we have to
5011 // use a splat constant.
5012 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5013 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5014 ExtractIdx = CstVal->getSExtValue();
5015 else
5016 UseSplat = true;
5017 }
5018
5019 unsigned End = getTransitionType()->getVectorNumElements();
5020 if (UseSplat)
5021 return ConstantVector::getSplat(End, Val);
5022
5023 SmallVector<Constant *, 4> ConstVec;
5024 UndefValue *UndefVal = UndefValue::get(Val->getType());
5025 for (unsigned Idx = 0; Idx != End; ++Idx) {
5026 if (Idx == ExtractIdx)
5027 ConstVec.push_back(Val);
5028 else
5029 ConstVec.push_back(UndefVal);
5030 }
5031 return ConstantVector::get(ConstVec);
5032 }
5033
5034 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5035 /// in \p Use can trigger undefined behavior.
5036 static bool canCauseUndefinedBehavior(const Instruction *Use,
5037 unsigned OperandIdx) {
5038 // This is not safe to introduce undef when the operand is on
5039 // the right hand side of a division-like instruction.
5040 if (OperandIdx != 1)
5041 return false;
5042 switch (Use->getOpcode()) {
5043 default:
5044 return false;
5045 case Instruction::SDiv:
5046 case Instruction::UDiv:
5047 case Instruction::SRem:
5048 case Instruction::URem:
5049 return true;
5050 case Instruction::FDiv:
5051 case Instruction::FRem:
5052 return !Use->hasNoNaNs();
5053 }
5054 llvm_unreachable(nullptr);
5055 }
5056
5057public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005058 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5059 const TargetTransformInfo &TTI, Instruction *Transition,
5060 unsigned CombineCost)
5061 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005062 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5063 assert(Transition && "Do not know how to promote null");
5064 }
5065
5066 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5067 bool canPromote(const Instruction *ToBePromoted) const {
5068 // We could support CastInst too.
5069 return isa<BinaryOperator>(ToBePromoted);
5070 }
5071
5072 /// \brief Check if it is profitable to promote \p ToBePromoted
5073 /// by moving downward the transition through.
5074 bool shouldPromote(const Instruction *ToBePromoted) const {
5075 // Promote only if all the operands can be statically expanded.
5076 // Indeed, we do not want to introduce any new kind of transitions.
5077 for (const Use &U : ToBePromoted->operands()) {
5078 const Value *Val = U.get();
5079 if (Val == getEndOfTransition()) {
5080 // If the use is a division and the transition is on the rhs,
5081 // we cannot promote the operation, otherwise we may create a
5082 // division by zero.
5083 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5084 return false;
5085 continue;
5086 }
5087 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5088 !isa<ConstantFP>(Val))
5089 return false;
5090 }
5091 // Check that the resulting operation is legal.
5092 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5093 if (!ISDOpcode)
5094 return false;
5095 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005096 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005097 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005098 }
5099
5100 /// \brief Check whether or not \p Use can be combined
5101 /// with the transition.
5102 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5103 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5104
5105 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5106 void enqueueForPromotion(Instruction *ToBePromoted) {
5107 InstsToBePromoted.push_back(ToBePromoted);
5108 }
5109
5110 /// \brief Set the instruction that will be combined with the transition.
5111 void recordCombineInstruction(Instruction *ToBeCombined) {
5112 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5113 CombineInst = ToBeCombined;
5114 }
5115
5116 /// \brief Promote all the instructions enqueued for promotion if it is
5117 /// is profitable.
5118 /// \return True if the promotion happened, false otherwise.
5119 bool promote() {
5120 // Check if there is something to promote.
5121 // Right now, if we do not have anything to combine with,
5122 // we assume the promotion is not profitable.
5123 if (InstsToBePromoted.empty() || !CombineInst)
5124 return false;
5125
5126 // Check cost.
5127 if (!StressStoreExtract && !isProfitableToPromote())
5128 return false;
5129
5130 // Promote.
5131 for (auto &ToBePromoted : InstsToBePromoted)
5132 promoteImpl(ToBePromoted);
5133 InstsToBePromoted.clear();
5134 return true;
5135 }
5136};
5137} // End of anonymous namespace.
5138
5139void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5140 // At this point, we know that all the operands of ToBePromoted but Def
5141 // can be statically promoted.
5142 // For Def, we need to use its parameter in ToBePromoted:
5143 // b = ToBePromoted ty1 a
5144 // Def = Transition ty1 b to ty2
5145 // Move the transition down.
5146 // 1. Replace all uses of the promoted operation by the transition.
5147 // = ... b => = ... Def.
5148 assert(ToBePromoted->getType() == Transition->getType() &&
5149 "The type of the result of the transition does not match "
5150 "the final type");
5151 ToBePromoted->replaceAllUsesWith(Transition);
5152 // 2. Update the type of the uses.
5153 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5154 Type *TransitionTy = getTransitionType();
5155 ToBePromoted->mutateType(TransitionTy);
5156 // 3. Update all the operands of the promoted operation with promoted
5157 // operands.
5158 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5159 for (Use &U : ToBePromoted->operands()) {
5160 Value *Val = U.get();
5161 Value *NewVal = nullptr;
5162 if (Val == Transition)
5163 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5164 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5165 isa<ConstantFP>(Val)) {
5166 // Use a splat constant if it is not safe to use undef.
5167 NewVal = getConstantVector(
5168 cast<Constant>(Val),
5169 isa<UndefValue>(Val) ||
5170 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5171 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005172 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5173 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005174 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5175 }
5176 Transition->removeFromParent();
5177 Transition->insertAfter(ToBePromoted);
5178 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5179}
5180
5181/// Some targets can do store(extractelement) with one instruction.
5182/// Try to push the extractelement towards the stores when the target
5183/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005184bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005185 unsigned CombineCost = UINT_MAX;
5186 if (DisableStoreExtract || !TLI ||
5187 (!StressStoreExtract &&
5188 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5189 Inst->getOperand(1), CombineCost)))
5190 return false;
5191
5192 // At this point we know that Inst is a vector to scalar transition.
5193 // Try to move it down the def-use chain, until:
5194 // - We can combine the transition with its single use
5195 // => we got rid of the transition.
5196 // - We escape the current basic block
5197 // => we would need to check that we are moving it at a cheaper place and
5198 // we do not do that for now.
5199 BasicBlock *Parent = Inst->getParent();
5200 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005201 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005202 // If the transition has more than one use, assume this is not going to be
5203 // beneficial.
5204 while (Inst->hasOneUse()) {
5205 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5206 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5207
5208 if (ToBePromoted->getParent() != Parent) {
5209 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5210 << ToBePromoted->getParent()->getName()
5211 << ") than the transition (" << Parent->getName() << ").\n");
5212 return false;
5213 }
5214
5215 if (VPH.canCombine(ToBePromoted)) {
5216 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5217 << "will be combined with: " << *ToBePromoted << '\n');
5218 VPH.recordCombineInstruction(ToBePromoted);
5219 bool Changed = VPH.promote();
5220 NumStoreExtractExposed += Changed;
5221 return Changed;
5222 }
5223
5224 DEBUG(dbgs() << "Try promoting.\n");
5225 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5226 return false;
5227
5228 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5229
5230 VPH.enqueueForPromotion(ToBePromoted);
5231 Inst = ToBePromoted;
5232 }
5233 return false;
5234}
5235
Sanjay Patelfc580a62015-09-21 23:03:16 +00005236bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005237 // Bail out if we inserted the instruction to prevent optimizations from
5238 // stepping on each other's toes.
5239 if (InsertedInsts.count(I))
5240 return false;
5241
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005242 if (PHINode *P = dyn_cast<PHINode>(I)) {
5243 // It is possible for very late stage optimizations (such as SimplifyCFG)
5244 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5245 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005246 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005247 P->replaceAllUsesWith(V);
5248 P->eraseFromParent();
5249 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005250 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005251 }
Chris Lattneree588de2011-01-15 07:29:01 +00005252 return false;
5253 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005254
Chris Lattneree588de2011-01-15 07:29:01 +00005255 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005256 // If the source of the cast is a constant, then this should have
5257 // already been constant folded. The only reason NOT to constant fold
5258 // it is if something (e.g. LSR) was careful to place the constant
5259 // evaluation in a block other than then one that uses it (e.g. to hoist
5260 // the address of globals out of a loop). If this is the case, we don't
5261 // want to forward-subst the cast.
5262 if (isa<Constant>(CI->getOperand(0)))
5263 return false;
5264
Mehdi Amini44ede332015-07-09 02:09:04 +00005265 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005266 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005267
Chris Lattneree588de2011-01-15 07:29:01 +00005268 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005269 /// Sink a zext or sext into its user blocks if the target type doesn't
5270 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005271 if (TLI &&
5272 TLI->getTypeAction(CI->getContext(),
5273 TLI->getValueType(*DL, CI->getType())) ==
5274 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005275 return SinkCast(CI);
5276 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005277 bool MadeChange = moveExtToFormExtLoad(I);
5278 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005279 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005280 }
Chris Lattneree588de2011-01-15 07:29:01 +00005281 return false;
5282 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005283
Chris Lattneree588de2011-01-15 07:29:01 +00005284 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005285 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005286 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005287
Chris Lattneree588de2011-01-15 07:29:01 +00005288 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005289 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005290 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005291 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005292 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005293 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5294 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005295 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005296 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005297 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005298
Chris Lattneree588de2011-01-15 07:29:01 +00005299 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005300 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005301 if (TLI) {
5302 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005303 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005304 SI->getOperand(0)->getType(), AS);
5305 }
Chris Lattneree588de2011-01-15 07:29:01 +00005306 return false;
5307 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005308
Yi Jiangd069f632014-04-21 19:34:27 +00005309 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5310
5311 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5312 BinOp->getOpcode() == Instruction::LShr)) {
5313 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5314 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005315 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005316
5317 return false;
5318 }
5319
Chris Lattneree588de2011-01-15 07:29:01 +00005320 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005321 if (GEPI->hasAllZeroIndices()) {
5322 /// The GEP operand must be a pointer, so must its result -> BitCast
5323 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5324 GEPI->getName(), GEPI);
5325 GEPI->replaceAllUsesWith(NC);
5326 GEPI->eraseFromParent();
5327 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005328 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005329 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005330 }
Chris Lattneree588de2011-01-15 07:29:01 +00005331 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005332 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005333
Chris Lattneree588de2011-01-15 07:29:01 +00005334 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005335 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005336
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005337 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005338 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005339
Tim Northoveraeb8e062014-02-19 10:02:43 +00005340 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005341 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005342
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005343 if (auto *Switch = dyn_cast<SwitchInst>(I))
5344 return optimizeSwitchInst(Switch);
5345
Quentin Colombetc32615d2014-10-31 17:52:53 +00005346 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005347 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005348
Chris Lattneree588de2011-01-15 07:29:01 +00005349 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005350}
5351
James Molloyf01488e2016-01-15 09:20:19 +00005352/// Given an OR instruction, check to see if this is a bitreverse
5353/// idiom. If so, insert the new intrinsic and return true.
5354static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5355 const TargetLowering &TLI) {
5356 if (!I.getType()->isIntegerTy() ||
5357 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5358 TLI.getValueType(DL, I.getType(), true)))
5359 return false;
5360
5361 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005362 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005363 return false;
5364 Instruction *LastInst = Insts.back();
5365 I.replaceAllUsesWith(LastInst);
5366 RecursivelyDeleteTriviallyDeadInstructions(&I);
5367 return true;
5368}
5369
Chris Lattnerf2836d12007-03-31 04:06:36 +00005370// In this pass we look for GEP and cast instructions that are used
5371// across basic blocks and rewrite them to improve basic-block-at-a-time
5372// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005373bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005374 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005375 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005376
Chris Lattner7a277142011-01-15 07:14:54 +00005377 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005378 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005379 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005380 if (ModifiedDT)
5381 return true;
5382 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005383
James Molloyf01488e2016-01-15 09:20:19 +00005384 bool MadeBitReverse = true;
5385 while (TLI && MadeBitReverse) {
5386 MadeBitReverse = false;
5387 for (auto &I : reverse(BB)) {
5388 if (makeBitReverse(I, *DL, *TLI)) {
5389 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005390 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005391 break;
5392 }
5393 }
5394 }
James Molloy3ef84c42016-01-15 10:36:01 +00005395 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005396
Chris Lattnerf2836d12007-03-31 04:06:36 +00005397 return MadeChange;
5398}
Devang Patel53771ba2011-08-18 00:50:51 +00005399
5400// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005401// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005402// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005403bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005404 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005405 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005406 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005407 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005408 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005409 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005410 // Leave dbg.values that refer to an alloca alone. These
5411 // instrinsics describe the address of a variable (= the alloca)
5412 // being taken. They should not be moved next to the alloca
5413 // (and to the beginning of the scope), but rather stay close to
5414 // where said address is used.
5415 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005416 PrevNonDbgInst = Insn;
5417 continue;
5418 }
5419
5420 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5421 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005422 // If VI is a phi in a block with an EHPad terminator, we can't insert
5423 // after it.
5424 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5425 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005426 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5427 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005428 if (isa<PHINode>(VI))
5429 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5430 else
5431 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005432 MadeChange = true;
5433 ++NumDbgValueMoved;
5434 }
5435 }
5436 }
5437 return MadeChange;
5438}
Tim Northovercea0abb2014-03-29 08:22:29 +00005439
5440// If there is a sequence that branches based on comparing a single bit
5441// against zero that can be combined into a single instruction, and the
5442// target supports folding these into a single instruction, sink the
5443// mask and compare into the branch uses. Do this before OptimizeBlock ->
5444// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5445// searched for.
5446bool CodeGenPrepare::sinkAndCmp(Function &F) {
5447 if (!EnableAndCmpSinking)
5448 return false;
5449 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5450 return false;
5451 bool MadeChange = false;
Sanjay Patel892f1672016-04-11 20:13:44 +00005452 for (BasicBlock &BB : F) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005453 // Does this BB end with the following?
5454 // %andVal = and %val, #single-bit-set
5455 // %icmpVal = icmp %andResult, 0
5456 // br i1 %cmpVal label %dest1, label %dest2"
Sanjay Patel892f1672016-04-11 20:13:44 +00005457 BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
Tim Northovercea0abb2014-03-29 08:22:29 +00005458 if (!Brcc || !Brcc->isConditional())
5459 continue;
5460 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005461 if (!Cmp || Cmp->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005462 continue;
5463 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5464 if (!Zero || !Zero->isZero())
5465 continue;
5466 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005467 if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005468 continue;
5469 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5470 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5471 continue;
Sanjay Patel892f1672016-04-11 20:13:44 +00005472 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
Tim Northovercea0abb2014-03-29 08:22:29 +00005473
5474 // Push the "and; icmp" for any users that are conditional branches.
5475 // Since there can only be one branch use per BB, we don't need to keep
5476 // track of which BBs we insert into.
Sanjay Patel892f1672016-04-11 20:13:44 +00005477 for (Use &TheUse : Cmp->uses()) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005478 // Find brcc use.
Sanjay Patel892f1672016-04-11 20:13:44 +00005479 BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
Tim Northovercea0abb2014-03-29 08:22:29 +00005480 if (!BrccUser || !BrccUser->isConditional())
5481 continue;
5482 BasicBlock *UserBB = BrccUser->getParent();
Sanjay Patel892f1672016-04-11 20:13:44 +00005483 if (UserBB == &BB) continue;
Tim Northovercea0abb2014-03-29 08:22:29 +00005484 DEBUG(dbgs() << "found Brcc use\n");
5485
5486 // Sink the "and; icmp" to use.
5487 MadeChange = true;
5488 BinaryOperator *NewAnd =
5489 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5490 BrccUser);
5491 CmpInst *NewCmp =
5492 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5493 "", BrccUser);
5494 TheUse = NewCmp;
5495 ++NumAndCmpsMoved;
5496 DEBUG(BrccUser->getParent()->dump());
5497 }
5498 }
5499 return MadeChange;
5500}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005501
5502/// \brief Scale down both weights to fit into uint32_t.
5503static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5504 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5505 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5506 NewTrue = NewTrue / Scale;
5507 NewFalse = NewFalse / Scale;
5508}
5509
5510/// \brief Some targets prefer to split a conditional branch like:
5511/// \code
5512/// %0 = icmp ne i32 %a, 0
5513/// %1 = icmp ne i32 %b, 0
5514/// %or.cond = or i1 %0, %1
5515/// br i1 %or.cond, label %TrueBB, label %FalseBB
5516/// \endcode
5517/// into multiple branch instructions like:
5518/// \code
5519/// bb1:
5520/// %0 = icmp ne i32 %a, 0
5521/// br i1 %0, label %TrueBB, label %bb2
5522/// bb2:
5523/// %1 = icmp ne i32 %b, 0
5524/// br i1 %1, label %TrueBB, label %FalseBB
5525/// \endcode
5526/// This usually allows instruction selection to do even further optimizations
5527/// and combine the compare with the branch instruction. Currently this is
5528/// applied for targets which have "cheap" jump instructions.
5529///
5530/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5531///
5532bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005533 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005534 return false;
5535
5536 bool MadeChange = false;
5537 for (auto &BB : F) {
5538 // Does this BB end with the following?
5539 // %cond1 = icmp|fcmp|binary instruction ...
5540 // %cond2 = icmp|fcmp|binary instruction ...
5541 // %cond.or = or|and i1 %cond1, cond2
5542 // br i1 %cond.or label %dest1, label %dest2"
5543 BinaryOperator *LogicOp;
5544 BasicBlock *TBB, *FBB;
5545 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5546 continue;
5547
Sanjay Patel42574202015-09-02 19:23:23 +00005548 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5549 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5550 continue;
5551
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005552 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005553 Value *Cond1, *Cond2;
5554 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5555 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005556 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005557 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5558 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005559 Opc = Instruction::Or;
5560 else
5561 continue;
5562
5563 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5564 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5565 continue;
5566
5567 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5568
5569 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005570 auto TmpBB =
5571 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5572 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005573
5574 // Update original basic block by using the first condition directly by the
5575 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005576 Br1->setCondition(Cond1);
5577 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005578
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005579 // Depending on the conditon we have to either replace the true or the false
5580 // successor of the original branch instruction.
5581 if (Opc == Instruction::And)
5582 Br1->setSuccessor(0, TmpBB);
5583 else
5584 Br1->setSuccessor(1, TmpBB);
5585
5586 // Fill in the new basic block.
5587 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005588 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5589 I->removeFromParent();
5590 I->insertBefore(Br2);
5591 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005592
5593 // Update PHI nodes in both successors. The original BB needs to be
5594 // replaced in one succesor's PHI nodes, because the branch comes now from
5595 // the newly generated BB (NewBB). In the other successor we need to add one
5596 // incoming edge to the PHI nodes, because both branch instructions target
5597 // now the same successor. Depending on the original branch condition
5598 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5599 // we perfrom the correct update for the PHI nodes.
5600 // This doesn't change the successor order of the just created branch
5601 // instruction (or any other instruction).
5602 if (Opc == Instruction::Or)
5603 std::swap(TBB, FBB);
5604
5605 // Replace the old BB with the new BB.
5606 for (auto &I : *TBB) {
5607 PHINode *PN = dyn_cast<PHINode>(&I);
5608 if (!PN)
5609 break;
5610 int i;
5611 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5612 PN->setIncomingBlock(i, TmpBB);
5613 }
5614
5615 // Add another incoming edge form the new BB.
5616 for (auto &I : *FBB) {
5617 PHINode *PN = dyn_cast<PHINode>(&I);
5618 if (!PN)
5619 break;
5620 auto *Val = PN->getIncomingValueForBlock(&BB);
5621 PN->addIncoming(Val, TmpBB);
5622 }
5623
5624 // Update the branch weights (from SelectionDAGBuilder::
5625 // FindMergedConditions).
5626 if (Opc == Instruction::Or) {
5627 // Codegen X | Y as:
5628 // BB1:
5629 // jmp_if_X TBB
5630 // jmp TmpBB
5631 // TmpBB:
5632 // jmp_if_Y TBB
5633 // jmp FBB
5634 //
5635
5636 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5637 // The requirement is that
5638 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5639 // = TrueProb for orignal BB.
5640 // Assuming the orignal weights are A and B, one choice is to set BB1's
5641 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5642 // assumes that
5643 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5644 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5645 // TmpBB, but the math is more complicated.
5646 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005647 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005648 uint64_t NewTrueWeight = TrueWeight;
5649 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5650 scaleWeights(NewTrueWeight, NewFalseWeight);
5651 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5652 .createBranchWeights(TrueWeight, FalseWeight));
5653
5654 NewTrueWeight = TrueWeight;
5655 NewFalseWeight = 2 * FalseWeight;
5656 scaleWeights(NewTrueWeight, NewFalseWeight);
5657 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5658 .createBranchWeights(TrueWeight, FalseWeight));
5659 }
5660 } else {
5661 // Codegen X & Y as:
5662 // BB1:
5663 // jmp_if_X TmpBB
5664 // jmp FBB
5665 // TmpBB:
5666 // jmp_if_Y TBB
5667 // jmp FBB
5668 //
5669 // This requires creation of TmpBB after CurBB.
5670
5671 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5672 // The requirement is that
5673 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5674 // = FalseProb for orignal BB.
5675 // Assuming the orignal weights are A and B, one choice is to set BB1's
5676 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5677 // assumes that
5678 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5679 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005680 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005681 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5682 uint64_t NewFalseWeight = FalseWeight;
5683 scaleWeights(NewTrueWeight, NewFalseWeight);
5684 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5685 .createBranchWeights(TrueWeight, FalseWeight));
5686
5687 NewTrueWeight = 2 * TrueWeight;
5688 NewFalseWeight = FalseWeight;
5689 scaleWeights(NewTrueWeight, NewFalseWeight);
5690 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5691 .createBranchWeights(TrueWeight, FalseWeight));
5692 }
5693 }
5694
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005695 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005696 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005697 ModifiedDT = true;
5698
5699 MadeChange = true;
5700
5701 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5702 TmpBB->dump());
5703 }
5704 return MadeChange;
5705}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005706
5707void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005708 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005709 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5710}