blob: 9f9bde40164ee157683c2d7cc1a60cdf4f40f8c4 [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
Eugene Zelenko900b6332017-08-29 22:32:07 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000019#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000021#include "llvm/ADT/SetVector.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000025#include "llvm/Analysis/BlockFrequencyInfo.h"
26#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000027#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000029#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000030#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000031#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000032#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000033#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000034#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000035#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/ISDOpcodes.h"
37#include "llvm/CodeGen/MachineValueType.h"
38#include "llvm/CodeGen/SelectionDAGNodes.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/CodeGen/TargetPassConfig.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000040#include "llvm/CodeGen/ValueTypes.h"
41#include "llvm/IR/Argument.h"
42#include "llvm/IR/Attributes.h"
43#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000044#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000045#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Constants.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000049#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000051#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000052#include "llvm/IR/GlobalValue.h"
53#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/IRBuilder.h"
55#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000056#include "llvm/IR/InstrTypes.h"
57#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Instructions.h"
59#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000060#include "llvm/IR/Intrinsics.h"
61#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000062#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000063#include "llvm/IR/Module.h"
64#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000065#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000066#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000067#include "llvm/IR/Type.h"
68#include "llvm/IR/Use.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000071#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000072#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000073#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000074#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000075#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000076#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000077#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000078#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000079#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000080#include "llvm/Support/ErrorHandling.h"
81#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000082#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000083#include "llvm/Target/TargetLowering.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000084#include "llvm/Target/TargetMachine.h"
85#include "llvm/Target/TargetOptions.h"
Hal Finkelc3998302014-04-12 00:59:48 +000086#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000087#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000088#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000089#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000090#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000091#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000092#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000093#include <algorithm>
94#include <cassert>
95#include <cstdint>
96#include <iterator>
97#include <limits>
98#include <memory>
99#include <utility>
100#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000101
Chris Lattnerf2836d12007-03-31 04:06:36 +0000102using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000103using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000104
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000105#define DEBUG_TYPE "codegenprepare"
106
Cameron Zwarichced753f2011-01-05 17:27:27 +0000107STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000108STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
109STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000110STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
111 "sunken Cmps");
112STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
113 "of sunken Casts");
114STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
115 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +0000116STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
117STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000118STATISTIC(NumAndsAdded,
119 "Number of and mask instructions added to form ext loads");
120STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000121STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000122STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000123STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000124STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000125
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000126STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
127STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
128STATISTIC(NumMemCmpGreaterThanMax,
129 "Number of memcmp calls with size greater than max size");
130STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
131
Cameron Zwarich338d3622011-03-11 21:52:04 +0000132static cl::opt<bool> DisableBranchOpts(
133 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
134 cl::desc("Disable branch optimizations in CodeGenPrepare"));
135
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000136static cl::opt<bool>
137 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
138 cl::desc("Disable GC optimizations in CodeGenPrepare"));
139
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000140static cl::opt<bool> DisableSelectToBranch(
141 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
142 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000143
Hal Finkelc3998302014-04-12 00:59:48 +0000144static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000145 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000146 cl::desc("Address sinking in CGP using GEPs."));
147
Tim Northovercea0abb2014-03-29 08:22:29 +0000148static cl::opt<bool> EnableAndCmpSinking(
149 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
150 cl::desc("Enable sinkinig and/cmp into branches."));
151
Quentin Colombetc32615d2014-10-31 17:52:53 +0000152static cl::opt<bool> DisableStoreExtract(
153 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
154 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
155
156static cl::opt<bool> StressStoreExtract(
157 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
158 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
159
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000160static cl::opt<bool> DisableExtLdPromotion(
161 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
162 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
163 "CodeGenPrepare"));
164
165static cl::opt<bool> StressExtLdPromotion(
166 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
167 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
168 "optimization in CodeGenPrepare"));
169
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000170static cl::opt<bool> DisablePreheaderProtect(
171 "disable-preheader-prot", cl::Hidden, cl::init(false),
172 cl::desc("Disable protection against removing loop preheaders"));
173
Dehao Chen302b69c2016-10-18 20:42:47 +0000174static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000175 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000176 cl::desc("Use profile info to add section prefix for hot/cold functions"));
177
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000178static cl::opt<unsigned> FreqRatioToSkipMerge(
179 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
180 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
181 "(frequency of destination block) is greater than this ratio"));
182
Wei Mia2f0b592016-12-22 19:44:45 +0000183static cl::opt<bool> ForceSplitStore(
184 "force-split-store", cl::Hidden, cl::init(false),
185 cl::desc("Force store splitting no matter what the target query says."));
186
Jun Bum Limdee55652017-04-03 19:20:07 +0000187static cl::opt<bool>
188EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
189 cl::desc("Enable merging of redundant sexts when one is dominating"
190 " the other."), cl::init(true));
191
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000192static cl::opt<unsigned> MemCmpNumLoadsPerBlock(
193 "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
194 cl::desc("The number of loads per basic block for inline expansion of "
195 "memcmp that is only being compared against zero."));
196
Eric Christopherc1ea1492008-09-24 05:32:41 +0000197namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000198
199using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
200using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
201using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
202using SExts = SmallVector<Instruction *, 16>;
203using ValueToSExts = DenseMap<Value *, SExts>;
204
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000205class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000206
Chris Lattner2dd09db2009-09-02 06:11:42 +0000207 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000208 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000209 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000210 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000211 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000212 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000213 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000214 const LoopInfo *LI;
Balaram Makamcddf3c52017-10-26 22:34:01 +0000215 DominatorTree *DT;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000216 std::unique_ptr<BlockFrequencyInfo> BFI;
217 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000218
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000219 /// As we scan instructions optimizing them, this is the next instruction
220 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000221 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000222
Evan Cheng0663f232011-03-21 01:19:09 +0000223 /// Keeps track of non-local addresses that have been sunk into a block.
224 /// This allows us to avoid inserting duplicate code for blocks with
225 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000226 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000227
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000228 /// Keeps track of all instructions inserted for the current function.
229 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000230
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000231 /// Keeps track of the type of the related instruction before their
232 /// promotion for the current function.
233 InstrToOrigTy PromotedInsts;
234
Jun Bum Limdee55652017-04-03 19:20:07 +0000235 /// Keep track of instructions removed during promotion.
236 SetOfInstrs RemovedInsts;
237
238 /// Keep track of sext chains based on their initial value.
239 DenseMap<Value *, Instruction *> SeenChainsForSExt;
240
241 /// Keep track of SExt promoted.
242 ValueToSExts ValToSExtendedUses;
243
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000244 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000245 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000246
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000247 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000248 bool OptSize;
249
Mehdi Amini4fe37982015-07-07 18:45:17 +0000250 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000251 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000252
Chris Lattnerf2836d12007-03-31 04:06:36 +0000253 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000254 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000255
256 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000257 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
258 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000259
Craig Topper4584cd52014-03-07 09:26:03 +0000260 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000261
Mehdi Amini117296c2016-10-01 02:56:57 +0000262 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000263
Craig Topper4584cd52014-03-07 09:26:03 +0000264 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000265 // FIXME: When we can selectively preserve passes, preserve the domtree.
Balaram Makamcddf3c52017-10-26 22:34:01 +0000266 AU.addRequired<DominatorTreeWrapperPass>();
Dehao Chen302b69c2016-10-18 20:42:47 +0000267 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000268 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000269 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000270 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000271 }
272
Chris Lattnerf2836d12007-03-31 04:06:36 +0000273 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000274 bool eliminateFallThrough(Function &F);
275 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000276 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000277 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
278 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000279 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
280 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000281 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
282 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000283 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000284 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000285 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000286 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000287 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000288 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000289 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000290 bool optimizeSelectInst(SelectInst *SI);
291 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000292 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000293 bool optimizeExtractElementInst(Instruction *Inst);
294 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
295 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000296 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
297 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
298 bool tryToPromoteExts(TypePromotionTransaction &TPT,
299 const SmallVectorImpl<Instruction *> &Exts,
300 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
301 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000302 bool mergeSExts(Function &F);
303 bool performAddressTypePromotion(
304 Instruction *&Inst,
305 bool AllowPromotionWithoutCommonHeader,
306 bool HasPromoted, TypePromotionTransaction &TPT,
307 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000308 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000309 bool simplifyOffsetableRelocate(Instruction &I);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000310 bool splitIndirectCriticalEdges(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000311 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000312
313} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000314
Devang Patel8c78a0b2007-05-03 01:11:54 +0000315char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000316
Matthias Braun1527baa2017-05-25 21:26:32 +0000317INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000318 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000319INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000320INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000321 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000322
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000323FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000324
Chris Lattnerf2836d12007-03-31 04:06:36 +0000325bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000326 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000327 return false;
328
Mehdi Amini4fe37982015-07-07 18:45:17 +0000329 DL = &F.getParent()->getDataLayout();
330
Chris Lattnerf2836d12007-03-31 04:06:36 +0000331 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000332 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000333 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000334 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000335 BFI.reset();
336 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000337
Devang Patel8f606d72011-03-24 15:35:25 +0000338 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000339 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
340 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000341 SubtargetInfo = TM->getSubtargetImpl(F);
342 TLI = SubtargetInfo->getTargetLowering();
343 TRI = SubtargetInfo->getRegisterInfo();
344 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000345 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000346 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000347 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Balaram Makamcddf3c52017-10-26 22:34:01 +0000348 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
349
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000350 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000351
Dehao Chen302b69c2016-10-18 20:42:47 +0000352 if (ProfileGuidedSectionPrefix) {
353 ProfileSummaryInfo *PSI =
354 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen775341a2017-03-23 23:14:11 +0000355 if (PSI->isFunctionHotInCallGraph(&F))
Dehao Chen302b69c2016-10-18 20:42:47 +0000356 F.setSectionPrefix(".hot");
Dehao Chen775341a2017-03-23 23:14:11 +0000357 else if (PSI->isFunctionColdInCallGraph(&F))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000358 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000359 }
360
Preston Gurdcdf540d2012-09-04 18:22:17 +0000361 /// This optimization identifies DIV instructions that can be
362 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000363 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000364 const DenseMap<unsigned int, unsigned int> &BypassWidths =
365 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000366 BasicBlock* BB = &*F.begin();
367 while (BB != nullptr) {
368 // bypassSlowDivision may create new BBs, but we don't want to reapply the
369 // optimization to those blocks.
370 BasicBlock* Next = BB->getNextNode();
371 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
372 BB = Next;
373 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000374 }
375
376 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000377 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000378 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000379
Devang Patel53771ba2011-08-18 00:50:51 +0000380 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000381 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000382 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000383 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000384
Geoff Berry5d534b62017-02-21 18:53:14 +0000385 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000386 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000387
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000388 // Split some critical edges where one of the sources is an indirect branch,
389 // to help generate sane code for PHIs involving such edges.
390 EverMadeChange |= splitIndirectCriticalEdges(F);
391
Chris Lattnerc3748562007-04-02 01:35:34 +0000392 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000393 while (MadeChange) {
394 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000395 SeenChainsForSExt.clear();
396 ValToSExtendedUses.clear();
397 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000398 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000399 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000400 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000401 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000402
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000403 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000404 if (ModifiedDTOnIteration)
405 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000406 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000407 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
408 MadeChange |= mergeSExts(F);
409
410 // Really free removed instructions during promotion.
411 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000412 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000413
Chris Lattnerf2836d12007-03-31 04:06:36 +0000414 EverMadeChange |= MadeChange;
415 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000416
417 SunkAddrs.clear();
418
Cameron Zwarich338d3622011-03-11 21:52:04 +0000419 if (!DisableBranchOpts) {
420 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000421 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000422 for (BasicBlock &BB : F) {
423 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
424 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000425 if (!MadeChange) continue;
426
427 for (SmallVectorImpl<BasicBlock*>::iterator
428 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
429 if (pred_begin(*II) == pred_end(*II))
430 WorkList.insert(*II);
431 }
432
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000433 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000434 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000435 while (!WorkList.empty()) {
436 BasicBlock *BB = *WorkList.begin();
437 WorkList.erase(BB);
438 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
439
440 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000441
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000442 for (SmallVectorImpl<BasicBlock*>::iterator
443 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
444 if (pred_begin(*II) == pred_end(*II))
445 WorkList.insert(*II);
446 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000447
Nadav Rotem70409992012-08-14 05:19:07 +0000448 // Merge pairs of basic blocks with unconditional branches, connected by
449 // a single edge.
450 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000451 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000452
Cameron Zwarich338d3622011-03-11 21:52:04 +0000453 EverMadeChange |= MadeChange;
454 }
455
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000456 if (!DisableGCOpts) {
457 SmallVector<Instruction *, 2> Statepoints;
458 for (BasicBlock &BB : F)
459 for (Instruction &I : BB)
460 if (isStatepoint(I))
461 Statepoints.push_back(&I);
462 for (auto &I : Statepoints)
463 EverMadeChange |= simplifyOffsetableRelocate(*I);
464 }
465
Chris Lattnerf2836d12007-03-31 04:06:36 +0000466 return EverMadeChange;
467}
468
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000469/// Merge basic blocks which are connected by a single edge, where one of the
470/// basic blocks has a single successor pointing to the other basic block,
471/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000472bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000473 bool Changed = false;
474 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000475 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000476 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000477 // If the destination block has a single pred, then this is a trivial
478 // edge, just collapse it.
479 BasicBlock *SinglePred = BB->getSinglePredecessor();
480
Evan Cheng64a223a2012-09-28 23:58:57 +0000481 // Don't merge if BB's address is taken.
482 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000483
484 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
485 if (Term && !Term->isConditional()) {
486 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000487 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000488 // Remember if SinglePred was the entry block of the function.
489 // If so, we will need to move BB back to the entry position.
490 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000491 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000492
493 if (isEntry && BB != &BB->getParent()->getEntryBlock())
494 BB->moveBefore(&BB->getParent()->getEntryBlock());
495
496 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000497 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000498 }
499 }
500 return Changed;
501}
502
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000503/// Find a destination block from BB if BB is mergeable empty block.
504BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
505 // If this block doesn't end with an uncond branch, ignore it.
506 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
507 if (!BI || !BI->isUnconditional())
508 return nullptr;
509
510 // If the instruction before the branch (skipping debug info) isn't a phi
511 // node, then other stuff is happening here.
512 BasicBlock::iterator BBI = BI->getIterator();
513 if (BBI != BB->begin()) {
514 --BBI;
515 while (isa<DbgInfoIntrinsic>(BBI)) {
516 if (BBI == BB->begin())
517 break;
518 --BBI;
519 }
520 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
521 return nullptr;
522 }
523
524 // Do not break infinite loops.
525 BasicBlock *DestBB = BI->getSuccessor(0);
526 if (DestBB == BB)
527 return nullptr;
528
529 if (!canMergeBlocks(BB, DestBB))
530 DestBB = nullptr;
531
532 return DestBB;
533}
534
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000535// Return the unique indirectbr predecessor of a block. This may return null
536// even if such a predecessor exists, if it's not useful for splitting.
537// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
538// predecessors of BB.
539static BasicBlock *
540findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
541 // If the block doesn't have any PHIs, we don't care about it, since there's
542 // no point in splitting it.
543 PHINode *PN = dyn_cast<PHINode>(BB->begin());
544 if (!PN)
545 return nullptr;
546
547 // Verify we have exactly one IBR predecessor.
548 // Conservatively bail out if one of the other predecessors is not a "regular"
549 // terminator (that is, not a switch or a br).
550 BasicBlock *IBB = nullptr;
551 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
552 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
553 TerminatorInst *PredTerm = PredBB->getTerminator();
554 switch (PredTerm->getOpcode()) {
555 case Instruction::IndirectBr:
556 if (IBB)
557 return nullptr;
558 IBB = PredBB;
559 break;
560 case Instruction::Br:
561 case Instruction::Switch:
562 OtherPreds.push_back(PredBB);
563 continue;
564 default:
565 return nullptr;
566 }
567 }
568
569 return IBB;
570}
571
572// Split critical edges where the source of the edge is an indirectbr
573// instruction. This isn't always possible, but we can handle some easy cases.
574// This is useful because MI is unable to split such critical edges,
575// which means it will not be able to sink instructions along those edges.
576// This is especially painful for indirect branches with many successors, where
577// we end up having to prepare all outgoing values in the origin block.
578//
579// Our normal algorithm for splitting critical edges requires us to update
580// the outgoing edges of the edge origin block, but for an indirectbr this
581// is hard, since it would require finding and updating the block addresses
582// the indirect branch uses. But if a block only has a single indirectbr
583// predecessor, with the others being regular branches, we can do it in a
584// different way.
585// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
586// We can split D into D0 and D1, where D0 contains only the PHIs from D,
587// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
588// create the following structure:
589// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
590bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
591 // Check whether the function has any indirectbrs, and collect which blocks
592 // they may jump to. Since most functions don't have indirect branches,
593 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
594 SmallSetVector<BasicBlock *, 16> Targets;
595 for (auto &BB : F) {
596 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
597 if (!IBI)
598 continue;
599
600 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
601 Targets.insert(IBI->getSuccessor(Succ));
602 }
603
604 if (Targets.empty())
605 return false;
606
607 bool Changed = false;
608 for (BasicBlock *Target : Targets) {
609 SmallVector<BasicBlock *, 16> OtherPreds;
610 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
611 // If we did not found an indirectbr, or the indirectbr is the only
612 // incoming edge, this isn't the kind of edge we're looking for.
613 if (!IBRPred || OtherPreds.empty())
614 continue;
615
616 // Don't even think about ehpads/landingpads.
617 Instruction *FirstNonPHI = Target->getFirstNonPHI();
618 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
619 continue;
620
621 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
622 // It's possible Target was its own successor through an indirectbr.
623 // In this case, the indirectbr now comes from BodyBlock.
624 if (IBRPred == Target)
625 IBRPred = BodyBlock;
626
627 // At this point Target only has PHIs, and BodyBlock has the rest of the
628 // block's body. Create a copy of Target that will be used by the "direct"
629 // preds.
630 ValueToValueMapTy VMap;
631 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
632
Brendon Cahoon7769a082017-04-17 19:11:04 +0000633 for (BasicBlock *Pred : OtherPreds) {
634 // If the target is a loop to itself, then the terminator of the split
635 // block needs to be updated.
636 if (Pred == Target)
637 BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
638 else
639 Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
640 }
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000641
642 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
643 // they are clones, so the number of PHIs are the same.
644 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
645 // (b) Leave that as the only edge in the "Indirect" PHI.
646 // (c) Merge the two in the body block.
647 BasicBlock::iterator Indirect = Target->begin(),
648 End = Target->getFirstNonPHI()->getIterator();
649 BasicBlock::iterator Direct = DirectSucc->begin();
650 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
651
652 assert(&*End == Target->getTerminator() &&
653 "Block was expected to only contain PHIs");
654
655 while (Indirect != End) {
656 PHINode *DirPHI = cast<PHINode>(Direct);
657 PHINode *IndPHI = cast<PHINode>(Indirect);
658
659 // Now, clean up - the direct block shouldn't get the indirect value,
660 // and vice versa.
661 DirPHI->removeIncomingValue(IBRPred);
662 Direct++;
663
664 // Advance the pointer here, to avoid invalidation issues when the old
665 // PHI is erased.
666 Indirect++;
667
668 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
669 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
670 IBRPred);
671
672 // Create a PHI in the body block, to merge the direct and indirect
673 // predecessors.
674 PHINode *MergePHI =
675 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
676 MergePHI->addIncoming(NewIndPHI, Target);
677 MergePHI->addIncoming(DirPHI, DirectSucc);
678
679 IndPHI->replaceAllUsesWith(MergePHI);
680 IndPHI->eraseFromParent();
681 }
682
683 Changed = true;
684 }
685
686 return Changed;
687}
688
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000689/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
690/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
691/// edges in ways that are non-optimal for isel. Start by eliminating these
692/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000693bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000694 SmallPtrSet<BasicBlock *, 16> Preheaders;
695 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
696 while (!LoopList.empty()) {
697 Loop *L = LoopList.pop_back_val();
698 LoopList.insert(LoopList.end(), L->begin(), L->end());
699 if (BasicBlock *Preheader = L->getLoopPreheader())
700 Preheaders.insert(Preheader);
701 }
702
Chris Lattnerc3748562007-04-02 01:35:34 +0000703 bool MadeChange = false;
704 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000705 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000706 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000707 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
708 if (!DestBB ||
709 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000710 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000711
Sanjay Patelfc580a62015-09-21 23:03:16 +0000712 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000713 MadeChange = true;
714 }
715 return MadeChange;
716}
717
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000718bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
719 BasicBlock *DestBB,
720 bool isPreheader) {
721 // Do not delete loop preheaders if doing so would create a critical edge.
722 // Loop preheaders can be good locations to spill registers. If the
723 // preheader is deleted and we create a critical edge, registers may be
724 // spilled in the loop body instead.
725 if (!DisablePreheaderProtect && isPreheader &&
726 !(BB->getSinglePredecessor() &&
727 BB->getSinglePredecessor()->getSingleSuccessor()))
728 return false;
729
730 // Try to skip merging if the unique predecessor of BB is terminated by a
731 // switch or indirect branch instruction, and BB is used as an incoming block
732 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
733 // add COPY instructions in the predecessor of BB instead of BB (if it is not
734 // merged). Note that the critical edge created by merging such blocks wont be
735 // split in MachineSink because the jump table is not analyzable. By keeping
736 // such empty block (BB), ISel will place COPY instructions in BB, not in the
737 // predecessor of BB.
738 BasicBlock *Pred = BB->getUniquePredecessor();
739 if (!Pred ||
740 !(isa<SwitchInst>(Pred->getTerminator()) ||
741 isa<IndirectBrInst>(Pred->getTerminator())))
742 return true;
743
744 if (BB->getTerminator() != BB->getFirstNonPHI())
745 return true;
746
747 // We use a simple cost heuristic which determine skipping merging is
748 // profitable if the cost of skipping merging is less than the cost of
749 // merging : Cost(skipping merging) < Cost(merging BB), where the
750 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
751 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
752 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
753 // Freq(Pred) / Freq(BB) > 2.
754 // Note that if there are multiple empty blocks sharing the same incoming
755 // value for the PHIs in the DestBB, we consider them together. In such
756 // case, Cost(merging BB) will be the sum of their frequencies.
757
758 if (!isa<PHINode>(DestBB->begin()))
759 return true;
760
761 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
Balaram Makamcddf3c52017-10-26 22:34:01 +0000762 SmallVector<PHINode *, 16> PNs;
763
764 for (auto DestBBI = DestBB->begin();
765 auto *DestPN = dyn_cast<PHINode>(&*DestBBI); ++DestBBI)
766 PNs.push_back(DestPN);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000767
768 // Find all other incoming blocks from which incoming values of all PHIs in
769 // DestBB are the same as the ones from BB.
770 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
771 ++PI) {
772 BasicBlock *DestBBPred = *PI;
773 if (DestBBPred == BB)
774 continue;
775
Balaram Makamcddf3c52017-10-26 22:34:01 +0000776 if (llvm::all_of(PNs, [&](PHINode *PN) {
777 return (PN->getIncomingValueForBlock(BB) ==
778 PN->getIncomingValueForBlock(DestBBPred));
779 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000780 SameIncomingValueBBs.insert(DestBBPred);
781 }
782
783 // See if all BB's incoming values are same as the value from Pred. In this
784 // case, no reason to skip merging because COPYs are expected to be place in
785 // Pred already.
786 if (SameIncomingValueBBs.count(Pred))
787 return true;
788
Balaram Makamcddf3c52017-10-26 22:34:01 +0000789 // Check to see if none of the phis have constant incoming values for BB and
790 // Pred dominates DestBB, in such case extra COPYs are likely not added, so
791 // there is no reason to skip merging.
792 if (DT->dominates(Pred, DestBB) && llvm::none_of(PNs, [BB](PHINode *PN) {
793 return isa<Constant>(PN->getIncomingValueForBlock(BB));
794 }))
795 return true;
796
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000797 if (!BFI) {
798 Function &F = *BB->getParent();
799 LoopInfo LI{DominatorTree(F)};
800 BPI.reset(new BranchProbabilityInfo(F, LI));
801 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
802 }
803
804 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
805 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
806
807 for (auto SameValueBB : SameIncomingValueBBs)
808 if (SameValueBB->getUniquePredecessor() == Pred &&
809 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
810 BBFreq += BFI->getBlockFreq(SameValueBB);
811
812 return PredFreq.getFrequency() <=
813 BBFreq.getFrequency() * FreqRatioToSkipMerge;
814}
815
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000816/// Return true if we can merge BB into DestBB if there is a single
817/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000818/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000819bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000820 const BasicBlock *DestBB) const {
821 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
822 // the successor. If there are more complex condition (e.g. preheaders),
823 // don't mess around with them.
824 BasicBlock::const_iterator BBI = BB->begin();
825 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000826 for (const User *U : PN->users()) {
827 const Instruction *UI = cast<Instruction>(U);
828 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000829 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000830 // If User is inside DestBB block and it is a PHINode then check
831 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000832 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000833 if (UI->getParent() == DestBB) {
834 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000835 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
836 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
837 if (Insn && Insn->getParent() == BB &&
838 Insn->getParent() != UPN->getIncomingBlock(I))
839 return false;
840 }
841 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000842 }
843 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000844
Chris Lattnerc3748562007-04-02 01:35:34 +0000845 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
846 // and DestBB may have conflicting incoming values for the block. If so, we
847 // can't merge the block.
848 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
849 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000850
Chris Lattnerc3748562007-04-02 01:35:34 +0000851 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000852 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000853 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
854 // It is faster to get preds from a PHI than with pred_iterator.
855 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
856 BBPreds.insert(BBPN->getIncomingBlock(i));
857 } else {
858 BBPreds.insert(pred_begin(BB), pred_end(BB));
859 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000860
Chris Lattnerc3748562007-04-02 01:35:34 +0000861 // Walk the preds of DestBB.
862 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
863 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
864 if (BBPreds.count(Pred)) { // Common predecessor?
865 BBI = DestBB->begin();
866 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
867 const Value *V1 = PN->getIncomingValueForBlock(Pred);
868 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000869
Chris Lattnerc3748562007-04-02 01:35:34 +0000870 // If V2 is a phi node in BB, look up what the mapped value will be.
871 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
872 if (V2PN->getParent() == BB)
873 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000874
Chris Lattnerc3748562007-04-02 01:35:34 +0000875 // If there is a conflict, bail out.
876 if (V1 != V2) return false;
877 }
878 }
879 }
880
881 return true;
882}
883
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000884/// Eliminate a basic block that has only phi's and an unconditional branch in
885/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000886void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000887 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
888 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000889
David Greene74e2d492010-01-05 01:27:11 +0000890 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000891
Chris Lattnerc3748562007-04-02 01:35:34 +0000892 // If the destination block has a single pred, then this is a trivial edge,
893 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000894 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000895 if (SinglePred != DestBB) {
896 // Remember if SinglePred was the entry block of the function. If so, we
897 // will need to move BB back to the entry position.
898 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Balaram Makamcddf3c52017-10-26 22:34:01 +0000899 MergeBasicBlockIntoOnlyPred(DestBB, DT);
Chris Lattner4059f432008-11-27 19:29:14 +0000900
Chris Lattner8a172da2008-11-28 19:54:49 +0000901 if (isEntry && BB != &BB->getParent()->getEntryBlock())
902 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000903
David Greene74e2d492010-01-05 01:27:11 +0000904 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000905 return;
906 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000907 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000908
Chris Lattnerc3748562007-04-02 01:35:34 +0000909 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
910 // to handle the new incoming edges it is about to have.
911 PHINode *PN;
912 for (BasicBlock::iterator BBI = DestBB->begin();
913 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
914 // Remove the incoming value for BB, and remember it.
915 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000916
Chris Lattnerc3748562007-04-02 01:35:34 +0000917 // Two options: either the InVal is a phi node defined in BB or it is some
918 // value that dominates BB.
919 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
920 if (InValPhi && InValPhi->getParent() == BB) {
921 // Add all of the input values of the input PHI as inputs of this phi.
922 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
923 PN->addIncoming(InValPhi->getIncomingValue(i),
924 InValPhi->getIncomingBlock(i));
925 } else {
926 // Otherwise, add one instance of the dominating value for each edge that
927 // we will be adding.
928 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
929 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
930 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
931 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000932 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
933 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000934 }
935 }
936 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000937
Chris Lattnerc3748562007-04-02 01:35:34 +0000938 // The PHIs are now updated, change everything that refers to BB to use
939 // DestBB and remove BB.
Balaram Makamcddf3c52017-10-26 22:34:01 +0000940 SmallVector<DominatorTree::UpdateType, 3> Updates;
941 for (auto *PredBB : predecessors(BB)) {
942 if (PredBB == BB)
943 continue;
944 DominatorTree::UpdateType UT = {DominatorTree::Delete, PredBB, BB};
945 if (!is_contained(Updates, UT)) {
946 Updates.push_back(UT);
947 if (PredBB != DestBB)
948 Updates.push_back({DominatorTree::Insert, PredBB, DestBB});
949 }
950 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000951 BB->replaceAllUsesWith(DestBB);
Balaram Makamcddf3c52017-10-26 22:34:01 +0000952 DT->applyUpdates(Updates);
953 BB->getTerminator()->eraseFromParent();
954 DT->deleteEdge(BB, DestBB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000955 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000956 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000957
David Greene74e2d492010-01-05 01:27:11 +0000958 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000959}
960
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000961// Computes a map of base pointer relocation instructions to corresponding
962// derived pointer relocation instructions given a vector of all relocate calls
963static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000964 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
965 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
966 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000967 // Collect information in two maps: one primarily for locating the base object
968 // while filling the second map; the second map is the final structure holding
969 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000970 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
971 for (auto *ThisRelocate : AllRelocateCalls) {
972 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
973 ThisRelocate->getDerivedPtrIndex());
974 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000975 }
976 for (auto &Item : RelocateIdxMap) {
977 std::pair<unsigned, unsigned> Key = Item.first;
978 if (Key.first == Key.second)
979 // Base relocation: nothing to insert
980 continue;
981
Manuel Jacob83eefa62016-01-05 04:03:00 +0000982 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000983 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000984
985 // We're iterating over RelocateIdxMap so we cannot modify it.
986 auto MaybeBase = RelocateIdxMap.find(BaseKey);
987 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000988 // TODO: We might want to insert a new base object relocate and gep off
989 // that, if there are enough derived object relocates.
990 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000991
992 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000993 }
994}
995
996// Accepts a GEP and extracts the operands into a vector provided they're all
997// small integer constants
998static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
999 SmallVectorImpl<Value *> &OffsetV) {
1000 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1001 // Only accept small constant integer operands
1002 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1003 if (!Op || Op->getZExtValue() > 20)
1004 return false;
1005 }
1006
1007 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1008 OffsetV.push_back(GEP->getOperand(i));
1009 return true;
1010}
1011
1012// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1013// replace, computes a replacement, and affects it.
1014static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +00001015simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1016 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001017 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +00001018 // We must ensure the relocation of derived pointer is defined after
1019 // relocation of base pointer. If we find a relocation corresponding to base
1020 // defined earlier than relocation of base then we move relocation of base
1021 // right before found relocation. We consider only relocation in the same
1022 // basic block as relocation of base. Relocations from other basic block will
1023 // be skipped by optimization and we do not care about them.
1024 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1025 &*R != RelocatedBase; ++R)
1026 if (auto RI = dyn_cast<GCRelocateInst>(R))
1027 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1028 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1029 RelocatedBase->moveBefore(RI);
1030 break;
1031 }
1032
Manuel Jacob83eefa62016-01-05 04:03:00 +00001033 for (GCRelocateInst *ToReplace : Targets) {
1034 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001035 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001036 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001037 // A duplicate relocate call. TODO: coalesce duplicates.
1038 continue;
1039 }
1040
Igor Laevskyf637b4a2015-11-03 18:37:40 +00001041 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1042 // Base and derived relocates are in different basic blocks.
1043 // In this case transform is only valid when base dominates derived
1044 // relocate. However it would be too expensive to check dominance
1045 // for each such relocate, so we skip the whole transformation.
1046 continue;
1047 }
1048
Manuel Jacob83eefa62016-01-05 04:03:00 +00001049 Value *Base = ToReplace->getBasePtr();
1050 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001051 if (!Derived || Derived->getPointerOperand() != Base)
1052 continue;
1053
1054 SmallVector<Value *, 2> OffsetV;
1055 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1056 continue;
1057
1058 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +00001059 assert(RelocatedBase->getNextNode() &&
1060 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +00001061
1062 // Insert after RelocatedBase
1063 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001064 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +00001065
1066 // If gc_relocate does not match the actual type, cast it to the right type.
1067 // In theory, there must be a bitcast after gc_relocate if the type does not
1068 // match, and we should reuse it to get the derived pointer. But it could be
1069 // cases like this:
1070 // bb1:
1071 // ...
1072 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1073 // br label %merge
1074 //
1075 // bb2:
1076 // ...
1077 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1078 // br label %merge
1079 //
1080 // merge:
1081 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1082 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1083 //
1084 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1085 // no matter there is already one or not. In this way, we can handle all cases, and
1086 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001087 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +00001088 if (RelocatedBase->getType() != Base->getType()) {
1089 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001090 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001091 }
David Blaikie68d535c2015-03-24 22:38:16 +00001092 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +00001093 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001094 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +00001095 // If the newly generated derived pointer's type does not match the original derived
1096 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001097 Value *ActualReplacement = Replacement;
1098 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +00001099 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001100 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001101 }
1102 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001103 ToReplace->eraseFromParent();
1104
1105 MadeChange = true;
1106 }
1107 return MadeChange;
1108}
1109
1110// Turns this:
1111//
1112// %base = ...
1113// %ptr = gep %base + 15
1114// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1115// %base' = relocate(%tok, i32 4, i32 4)
1116// %ptr' = relocate(%tok, i32 4, i32 5)
1117// %val = load %ptr'
1118//
1119// into this:
1120//
1121// %base = ...
1122// %ptr = gep %base + 15
1123// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1124// %base' = gc.relocate(%tok, i32 4, i32 4)
1125// %ptr' = gep %base' + 15
1126// %val = load %ptr'
1127bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1128 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001129 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001130
1131 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001132 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001133 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001134 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001135
1136 // We need atleast one base pointer relocation + one derived pointer
1137 // relocation to mangle
1138 if (AllRelocateCalls.size() < 2)
1139 return false;
1140
1141 // RelocateInstMap is a mapping from the base relocate instruction to the
1142 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001143 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001144 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1145 if (RelocateInstMap.empty())
1146 return false;
1147
1148 for (auto &Item : RelocateInstMap)
1149 // Item.first is the RelocatedBase to offset against
1150 // Item.second is the vector of Targets to replace
1151 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1152 return MadeChange;
1153}
1154
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001155/// SinkCast - Sink the specified cast instruction into its user blocks
1156static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001157 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001158
Chris Lattnerf2836d12007-03-31 04:06:36 +00001159 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001160 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001161
Chris Lattnerf2836d12007-03-31 04:06:36 +00001162 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001163 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001164 UI != E; ) {
1165 Use &TheUse = UI.getUse();
1166 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001167
Chris Lattnerf2836d12007-03-31 04:06:36 +00001168 // Figure out which BB this cast is used in. For PHI's this is the
1169 // appropriate predecessor block.
1170 BasicBlock *UserBB = User->getParent();
1171 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001172 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001173 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001174
Chris Lattnerf2836d12007-03-31 04:06:36 +00001175 // Preincrement use iterator so we don't invalidate it.
1176 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001177
David Majnemer0c80e2e2016-04-27 19:36:38 +00001178 // The first insertion point of a block containing an EH pad is after the
1179 // pad. If the pad is the user, we cannot sink the cast past the pad.
1180 if (User->isEHPad())
1181 continue;
1182
Andrew Kaylord0430e82015-11-23 19:16:15 +00001183 // If the block selected to receive the cast is an EH pad that does not
1184 // allow non-PHI instructions before the terminator, we can't sink the
1185 // cast.
1186 if (UserBB->getTerminator()->isEHPad())
1187 continue;
1188
Chris Lattnerf2836d12007-03-31 04:06:36 +00001189 // If this user is in the same block as the cast, don't change the cast.
1190 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001191
Chris Lattnerf2836d12007-03-31 04:06:36 +00001192 // If we have already inserted a cast into this block, use it.
1193 CastInst *&InsertedCast = InsertedCasts[UserBB];
1194
1195 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001196 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001197 assert(InsertPt != UserBB->end());
1198 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1199 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001200 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001201
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001202 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001203 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001204 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001205 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001206 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001207
Chris Lattnerf2836d12007-03-31 04:06:36 +00001208 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001209 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001210 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001211 MadeChange = true;
1212 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001213
Chris Lattnerf2836d12007-03-31 04:06:36 +00001214 return MadeChange;
1215}
1216
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001217/// If the specified cast instruction is a noop copy (e.g. it's casting from
1218/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1219/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001220///
1221/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001222static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1223 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001224 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1225 // than sinking only nop casts, but is helpful on some platforms.
1226 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1227 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1228 ASC->getDestAddressSpace()))
1229 return false;
1230 }
1231
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001232 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001233 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1234 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001235
1236 // This is an fp<->int conversion?
1237 if (SrcVT.isInteger() != DstVT.isInteger())
1238 return false;
1239
1240 // If this is an extension, it will be a zero or sign extension, which
1241 // isn't a noop.
1242 if (SrcVT.bitsLT(DstVT)) return false;
1243
1244 // If these values will be promoted, find out what they will be promoted
1245 // to. This helps us consider truncates on PPC as noop copies when they
1246 // are.
1247 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1248 TargetLowering::TypePromoteInteger)
1249 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1250 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1251 TargetLowering::TypePromoteInteger)
1252 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1253
1254 // If, after promotion, these are the same types, this is a noop copy.
1255 if (SrcVT != DstVT)
1256 return false;
1257
1258 return SinkCast(CI);
1259}
1260
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001261/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1262/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001263///
1264/// Return true if any changes were made.
1265static bool CombineUAddWithOverflow(CmpInst *CI) {
1266 Value *A, *B;
1267 Instruction *AddI;
1268 if (!match(CI,
1269 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1270 return false;
1271
1272 Type *Ty = AddI->getType();
1273 if (!isa<IntegerType>(Ty))
1274 return false;
1275
1276 // We don't want to move around uses of condition values this late, so we we
1277 // check if it is legal to create the call to the intrinsic in the basic
1278 // block containing the icmp:
1279
1280 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1281 return false;
1282
1283#ifndef NDEBUG
1284 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1285 // for now:
1286 if (AddI->hasOneUse())
1287 assert(*AddI->user_begin() == CI && "expected!");
1288#endif
1289
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001290 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001291 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1292
1293 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1294
1295 auto *UAddWithOverflow =
1296 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1297 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1298 auto *Overflow =
1299 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1300
1301 CI->replaceAllUsesWith(Overflow);
1302 AddI->replaceAllUsesWith(UAdd);
1303 CI->eraseFromParent();
1304 AddI->eraseFromParent();
1305 return true;
1306}
1307
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001308/// Sink the given CmpInst into user blocks to reduce the number of virtual
1309/// registers that must be created and coalesced. This is a clear win except on
1310/// targets with multiple condition code registers (PowerPC), where it might
1311/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001312///
1313/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001314static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001315 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001316
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001317 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001318 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001319 return false;
1320
1321 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001322 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001323
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001324 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001325 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001326 UI != E; ) {
1327 Use &TheUse = UI.getUse();
1328 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001329
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001330 // Preincrement use iterator so we don't invalidate it.
1331 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001332
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001333 // Don't bother for PHI nodes.
1334 if (isa<PHINode>(User))
1335 continue;
1336
1337 // Figure out which BB this cmp is used in.
1338 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001339
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001340 // If this user is in the same block as the cmp, don't change the cmp.
1341 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001342
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001343 // If we have already inserted a cmp into this block, use it.
1344 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1345
1346 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001347 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001348 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001349 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001350 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1351 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001352 // Propagate the debug info.
1353 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001354 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001355
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001356 // Replace a use of the cmp with a use of the new cmp.
1357 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001358 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001359 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001360 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001361
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001362 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001363 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001364 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001365 MadeChange = true;
1366 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001367
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001368 return MadeChange;
1369}
1370
Peter Zotovf87e5502016-04-03 17:11:53 +00001371static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001372 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001373 return true;
1374
1375 if (CombineUAddWithOverflow(CI))
1376 return true;
1377
1378 return false;
1379}
1380
Geoff Berry5d534b62017-02-21 18:53:14 +00001381/// Duplicate and sink the given 'and' instruction into user blocks where it is
1382/// used in a compare to allow isel to generate better code for targets where
1383/// this operation can be combined.
1384///
1385/// Return true if any changes are made.
1386static bool sinkAndCmp0Expression(Instruction *AndI,
1387 const TargetLowering &TLI,
1388 SetOfInstrs &InsertedInsts) {
1389 // Double-check that we're not trying to optimize an instruction that was
1390 // already optimized by some other part of this pass.
1391 assert(!InsertedInsts.count(AndI) &&
1392 "Attempting to optimize already optimized and instruction");
1393 (void) InsertedInsts;
1394
1395 // Nothing to do for single use in same basic block.
1396 if (AndI->hasOneUse() &&
1397 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1398 return false;
1399
1400 // Try to avoid cases where sinking/duplicating is likely to increase register
1401 // pressure.
1402 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1403 !isa<ConstantInt>(AndI->getOperand(1)) &&
1404 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1405 return false;
1406
1407 for (auto *U : AndI->users()) {
1408 Instruction *User = cast<Instruction>(U);
1409
1410 // Only sink for and mask feeding icmp with 0.
1411 if (!isa<ICmpInst>(User))
1412 return false;
1413
1414 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1415 if (!CmpC || !CmpC->isZero())
1416 return false;
1417 }
1418
1419 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1420 return false;
1421
1422 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1423 DEBUG(AndI->getParent()->dump());
1424
1425 // Push the 'and' into the same block as the icmp 0. There should only be
1426 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1427 // others, so we don't need to keep track of which BBs we insert into.
1428 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1429 UI != E; ) {
1430 Use &TheUse = UI.getUse();
1431 Instruction *User = cast<Instruction>(*UI);
1432
1433 // Preincrement use iterator so we don't invalidate it.
1434 ++UI;
1435
1436 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1437
1438 // Keep the 'and' in the same place if the use is already in the same block.
1439 Instruction *InsertPt =
1440 User->getParent() == AndI->getParent() ? AndI : User;
1441 Instruction *InsertedAnd =
1442 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1443 AndI->getOperand(1), "", InsertPt);
1444 // Propagate the debug info.
1445 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1446
1447 // Replace a use of the 'and' with a use of the new 'and'.
1448 TheUse = InsertedAnd;
1449 ++NumAndUses;
1450 DEBUG(User->getParent()->dump());
1451 }
1452
1453 // We removed all uses, nuke the and.
1454 AndI->eraseFromParent();
1455 return true;
1456}
1457
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001458/// Check if the candidates could be combined with a shift instruction, which
1459/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001460/// 1. Truncate instruction
1461/// 2. And instruction and the imm is a mask of the low bits:
1462/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001463static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001464 if (!isa<TruncInst>(User)) {
1465 if (User->getOpcode() != Instruction::And ||
1466 !isa<ConstantInt>(User->getOperand(1)))
1467 return false;
1468
Quentin Colombetd4f44692014-04-22 01:20:34 +00001469 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001470
Quentin Colombetd4f44692014-04-22 01:20:34 +00001471 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001472 return false;
1473 }
1474 return true;
1475}
1476
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001477/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001478static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001479SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1480 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001481 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001482 BasicBlock *UserBB = User->getParent();
1483 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1484 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1485 bool MadeChange = false;
1486
1487 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1488 TruncE = TruncI->user_end();
1489 TruncUI != TruncE;) {
1490
1491 Use &TruncTheUse = TruncUI.getUse();
1492 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1493 // Preincrement use iterator so we don't invalidate it.
1494
1495 ++TruncUI;
1496
1497 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1498 if (!ISDOpcode)
1499 continue;
1500
Tim Northovere2239ff2014-07-29 10:20:22 +00001501 // If the use is actually a legal node, there will not be an
1502 // implicit truncate.
1503 // FIXME: always querying the result type is just an
1504 // approximation; some nodes' legality is determined by the
1505 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001506 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001507 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001508 continue;
1509
1510 // Don't bother for PHI nodes.
1511 if (isa<PHINode>(TruncUser))
1512 continue;
1513
1514 BasicBlock *TruncUserBB = TruncUser->getParent();
1515
1516 if (UserBB == TruncUserBB)
1517 continue;
1518
1519 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1520 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1521
1522 if (!InsertedShift && !InsertedTrunc) {
1523 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001524 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001525 // Sink the shift
1526 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001527 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1528 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001529 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001530 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1531 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001532
1533 // Sink the trunc
1534 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1535 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001536 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001537
1538 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001539 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001540
1541 MadeChange = true;
1542
1543 TruncTheUse = InsertedTrunc;
1544 }
1545 }
1546 return MadeChange;
1547}
1548
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001549/// Sink the shift *right* instruction into user blocks if the uses could
1550/// potentially be combined with this shift instruction and generate BitExtract
1551/// instruction. It will only be applied if the architecture supports BitExtract
1552/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001553/// BB1:
1554/// %x.extract.shift = lshr i64 %arg1, 32
1555/// BB2:
1556/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1557/// ==>
1558///
1559/// BB2:
1560/// %x.extract.shift.1 = lshr i64 %arg1, 32
1561/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1562///
1563/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1564/// instruction.
1565/// Return true if any changes are made.
1566static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001567 const TargetLowering &TLI,
1568 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001569 BasicBlock *DefBB = ShiftI->getParent();
1570
1571 /// Only insert instructions in each block once.
1572 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1573
Mehdi Amini44ede332015-07-09 02:09:04 +00001574 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001575
1576 bool MadeChange = false;
1577 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1578 UI != E;) {
1579 Use &TheUse = UI.getUse();
1580 Instruction *User = cast<Instruction>(*UI);
1581 // Preincrement use iterator so we don't invalidate it.
1582 ++UI;
1583
1584 // Don't bother for PHI nodes.
1585 if (isa<PHINode>(User))
1586 continue;
1587
1588 if (!isExtractBitsCandidateUse(User))
1589 continue;
1590
1591 BasicBlock *UserBB = User->getParent();
1592
1593 if (UserBB == DefBB) {
1594 // If the shift and truncate instruction are in the same BB. The use of
1595 // the truncate(TruncUse) may still introduce another truncate if not
1596 // legal. In this case, we would like to sink both shift and truncate
1597 // instruction to the BB of TruncUse.
1598 // for example:
1599 // BB1:
1600 // i64 shift.result = lshr i64 opnd, imm
1601 // trunc.result = trunc shift.result to i16
1602 //
1603 // BB2:
1604 // ----> We will have an implicit truncate here if the architecture does
1605 // not have i16 compare.
1606 // cmp i16 trunc.result, opnd2
1607 //
1608 if (isa<TruncInst>(User) && shiftIsLegal
1609 // If the type of the truncate is legal, no trucate will be
1610 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001611 &&
1612 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001613 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001614 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001615
1616 continue;
1617 }
1618 // If we have already inserted a shift into this block, use it.
1619 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1620
1621 if (!InsertedShift) {
1622 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001623 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001624
1625 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001626 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1627 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001628 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001629 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1630 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001631
1632 MadeChange = true;
1633 }
1634
1635 // Replace a use of the shift with a use of the new shift.
1636 TheUse = InsertedShift;
1637 }
1638
1639 // If we removed all uses, nuke the shift.
1640 if (ShiftI->use_empty())
1641 ShiftI->eraseFromParent();
1642
1643 return MadeChange;
1644}
1645
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001646/// If counting leading or trailing zeros is an expensive operation and a zero
1647/// input is defined, add a check for zero to avoid calling the intrinsic.
1648///
1649/// We want to transform:
1650/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1651///
1652/// into:
1653/// entry:
1654/// %cmpz = icmp eq i64 %A, 0
1655/// br i1 %cmpz, label %cond.end, label %cond.false
1656/// cond.false:
1657/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1658/// br label %cond.end
1659/// cond.end:
1660/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1661///
1662/// If the transform is performed, return true and set ModifiedDT to true.
1663static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1664 const TargetLowering *TLI,
1665 const DataLayout *DL,
1666 bool &ModifiedDT) {
1667 if (!TLI || !DL)
1668 return false;
1669
1670 // If a zero input is undefined, it doesn't make sense to despeculate that.
1671 if (match(CountZeros->getOperand(1), m_One()))
1672 return false;
1673
1674 // If it's cheap to speculate, there's nothing to do.
1675 auto IntrinsicID = CountZeros->getIntrinsicID();
1676 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1677 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1678 return false;
1679
1680 // Only handle legal scalar cases. Anything else requires too much work.
1681 Type *Ty = CountZeros->getType();
1682 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001683 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001684 return false;
1685
1686 // The intrinsic will be sunk behind a compare against zero and branch.
1687 BasicBlock *StartBlock = CountZeros->getParent();
1688 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1689
1690 // Create another block after the count zero intrinsic. A PHI will be added
1691 // in this block to select the result of the intrinsic or the bit-width
1692 // constant if the input to the intrinsic is zero.
1693 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1694 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1695
1696 // Set up a builder to create a compare, conditional branch, and PHI.
1697 IRBuilder<> Builder(CountZeros->getContext());
1698 Builder.SetInsertPoint(StartBlock->getTerminator());
1699 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1700
1701 // Replace the unconditional branch that was created by the first split with
1702 // a compare against zero and a conditional branch.
1703 Value *Zero = Constant::getNullValue(Ty);
1704 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1705 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1706 StartBlock->getTerminator()->eraseFromParent();
1707
1708 // Create a PHI in the end block to select either the output of the intrinsic
1709 // or the bit width of the operand.
1710 Builder.SetInsertPoint(&EndBlock->front());
1711 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1712 CountZeros->replaceAllUsesWith(PN);
1713 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1714 PN->addIncoming(BitWidth, StartBlock);
1715 PN->addIncoming(CountZeros, CallBlock);
1716
1717 // We are explicitly handling the zero case, so we can set the intrinsic's
1718 // undefined zero argument to 'true'. This will also prevent reprocessing the
1719 // intrinsic; we only despeculate when a zero input is defined.
1720 CountZeros->setArgOperand(1, Builder.getTrue());
1721 ModifiedDT = true;
1722 return true;
1723}
1724
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001725namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001726
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001727// This class provides helper functions to expand a memcmp library call into an
1728// inline expansion.
1729class MemCmpExpansion {
1730 struct ResultBlock {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001731 BasicBlock *BB = nullptr;
1732 PHINode *PhiSrc1 = nullptr;
1733 PHINode *PhiSrc2 = nullptr;
1734
1735 ResultBlock() = default;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001736 };
1737
Clement Courbet0c7cd072017-10-25 11:02:09 +00001738 CallInst *const CI;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001739 ResultBlock ResBlock;
Clement Courbet0c7cd072017-10-25 11:02:09 +00001740 const uint64_t Size;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001741 unsigned MaxLoadSize;
Clement Courbet0c7cd072017-10-25 11:02:09 +00001742 uint64_t NumLoads;
1743 uint64_t NumLoadsNonOneByte;
1744 const uint64_t NumLoadsPerBlock;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001745 std::vector<BasicBlock *> LoadCmpBlocks;
1746 BasicBlock *EndBlock;
1747 PHINode *PhiRes;
Clement Courbet0c7cd072017-10-25 11:02:09 +00001748 const bool IsUsedForZeroCmp;
Sanjay Patel2843cad2017-06-09 23:01:05 +00001749 const DataLayout &DL;
Sanjay Patel9a4ce0c2017-06-27 18:18:42 +00001750 IRBuilder<> Builder;
Clement Courbet0c7cd072017-10-25 11:02:09 +00001751 // Represents the decomposition in blocks of the expansion. For example,
1752 // comparing 33 bytes on X86+sse can be done with 2x16-byte loads and
1753 // 1x1-byte load, which would be represented as [{16, 0}, {16, 16}, {32, 1}.
1754 // TODO(courbet): Involve the target more in this computation. On X86, 7
1755 // bytes can be done more efficiently with two overlaping 4-byte loads than
1756 // covering the interval with [{4, 0},{2, 4},{1, 6}}.
1757 struct LoadEntry {
1758 LoadEntry(unsigned LoadSize, uint64_t Offset)
1759 : LoadSize(LoadSize), Offset(Offset) {
1760 assert(Offset % LoadSize == 0 && "invalid load entry");
1761 }
Sanjay Patel2843cad2017-06-09 23:01:05 +00001762
Clement Courbet0c7cd072017-10-25 11:02:09 +00001763 uint64_t getGEPIndex() const { return Offset / LoadSize; }
1764
1765 // The size of the load for this block, in bytes.
1766 const unsigned LoadSize;
1767 // The offset of this load WRT the base pointer, in bytes.
1768 const uint64_t Offset;
1769 };
1770 SmallVector<LoadEntry, 8> LoadSequence;
1771 void computeLoadSequence();
1772
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001773 void createLoadCmpBlocks();
1774 void createResultBlock();
1775 void setupResultBlockPHINodes();
1776 void setupEndBlockPHINodes();
Clement Courbet0c7cd072017-10-25 11:02:09 +00001777 Value *getCompareLoadPairs(unsigned BlockIndex, unsigned &LoadIndex);
1778 void emitLoadCompareBlock(unsigned BlockIndex);
1779 void emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
1780 unsigned &LoadIndex);
1781 void emitLoadCompareByteBlock(unsigned BlockIndex, unsigned GEPIndex);
Sanjay Patel2843cad2017-06-09 23:01:05 +00001782 void emitMemCmpResultBlock();
Clement Courbet0c7cd072017-10-25 11:02:09 +00001783 Value *getMemCmpExpansionZeroCase();
1784 Value *getMemCmpEqZeroOneBlock();
1785 Value *getMemCmpOneBlock();
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001786
Clement Courbet0c7cd072017-10-25 11:02:09 +00001787 // Computes the decomposition. THis is the common code to compute the number
1788 // of loads and the actual load sequence. `callback` is called with each load
1789 // size and number of loads for the block size.
1790 template <typename CallBackT>
1791 void getDecomposition(CallBackT callback) const;
1792
1793 public:
Sanjay Patelcf531ca2017-06-07 15:05:13 +00001794 MemCmpExpansion(CallInst *CI, uint64_t Size, unsigned MaxLoadSize,
Sanjay Patel2843cad2017-06-09 23:01:05 +00001795 unsigned NumLoadsPerBlock, const DataLayout &DL);
Eugene Zelenko900b6332017-08-29 22:32:07 +00001796
Clement Courbet0c7cd072017-10-25 11:02:09 +00001797 unsigned getNumBlocks();
1798 uint64_t getNumLoads() const { return NumLoads; }
1799
1800 Value *getMemCmpExpansion();
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001801};
1802
Eugene Zelenko900b6332017-08-29 22:32:07 +00001803} // end anonymous namespace
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001804
1805// Initialize the basic block structure required for expansion of memcmp call
1806// with given maximum load size and memcmp size parameter.
1807// This structure includes:
1808// 1. A list of load compare blocks - LoadCmpBlocks.
1809// 2. An EndBlock, split from original instruction point, which is the block to
1810// return from.
1811// 3. ResultBlock, block to branch to for early exit when a
1812// LoadCmpBlock finds a difference.
Clement Courbet0c7cd072017-10-25 11:02:09 +00001813MemCmpExpansion::MemCmpExpansion(CallInst *const CI, uint64_t Size,
1814 const unsigned MaxLoadSize,
1815 const unsigned LoadsPerBlock,
Sanjay Patel2843cad2017-06-09 23:01:05 +00001816 const DataLayout &TheDataLayout)
Clement Courbet0c7cd072017-10-25 11:02:09 +00001817 : CI(CI),
1818 Size(Size),
1819 MaxLoadSize(MaxLoadSize),
1820 NumLoads(0),
1821 NumLoadsNonOneByte(0),
1822 NumLoadsPerBlock(LoadsPerBlock),
1823 IsUsedForZeroCmp(isOnlyUsedInZeroEqualityComparison(CI)),
1824 DL(TheDataLayout),
1825 Builder(CI) {
1826 // Scale the max size down if the target can load more bytes than we need.
1827 while (this->MaxLoadSize > Size) {
1828 this->MaxLoadSize /= 2;
Martin Bohme678c3e32017-10-24 20:40:02 +00001829 }
Clement Courbet0c7cd072017-10-25 11:02:09 +00001830 // Compute the number of loads. At that point we don't want to compute the
1831 // actual decomposition because it might be too large to fit in memory.
1832 getDecomposition([this](unsigned LoadSize, uint64_t NumLoadsForSize) {
1833 NumLoads += NumLoadsForSize;
1834 });
1835}
Martin Bohme678c3e32017-10-24 20:40:02 +00001836
Clement Courbet0c7cd072017-10-25 11:02:09 +00001837template <typename CallBackT>
1838void MemCmpExpansion::getDecomposition(CallBackT callback) const {
1839 unsigned LoadSize = this->MaxLoadSize;
1840 assert(Size > 0 && "zero blocks");
1841 uint64_t CurSize = Size;
1842 while (CurSize) {
1843 assert(LoadSize > 0 && "zero load size");
1844 const uint64_t NumLoadsForThisSize = CurSize / LoadSize;
1845 if (NumLoadsForThisSize > 0) {
1846 callback(LoadSize, NumLoadsForThisSize);
1847 CurSize = CurSize % LoadSize;
1848 }
1849 // FIXME: This can result in a non-native load size (e.g. X86-32+SSE can
1850 // load 16 and 4 but not 8), which throws the load count off (e.g. in the
1851 // aforementioned case, 16 bytes will count for 2 loads but will generate
1852 // 4).
1853 LoadSize /= 2;
1854 }
1855}
1856
1857void MemCmpExpansion::computeLoadSequence() {
1858 uint64_t Offset = 0;
1859 getDecomposition(
1860 [this, &Offset](unsigned LoadSize, uint64_t NumLoadsForSize) {
1861 for (uint64_t I = 0; I < NumLoadsForSize; ++I) {
1862 LoadSequence.push_back({LoadSize, Offset});
1863 Offset += LoadSize;
1864 }
1865 if (LoadSize > 1) {
1866 ++NumLoadsNonOneByte;
1867 }
1868 });
1869 assert(LoadSequence.size() == getNumLoads() && "mismatch in numbe rof loads");
1870}
1871
1872unsigned MemCmpExpansion::getNumBlocks() {
1873 if (IsUsedForZeroCmp)
1874 return getNumLoads() / NumLoadsPerBlock +
1875 (getNumLoads() % NumLoadsPerBlock != 0 ? 1 : 0);
1876 return getNumLoads();
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001877}
1878
1879void MemCmpExpansion::createLoadCmpBlocks() {
Clement Courbet0c7cd072017-10-25 11:02:09 +00001880 for (unsigned i = 0; i < getNumBlocks(); i++) {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001881 BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
1882 EndBlock->getParent(), EndBlock);
1883 LoadCmpBlocks.push_back(BB);
1884 }
1885}
1886
1887void MemCmpExpansion::createResultBlock() {
1888 ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
1889 EndBlock->getParent(), EndBlock);
1890}
1891
1892// This function creates the IR instructions for loading and comparing 1 byte.
Sanjay Patelab0ecc02017-06-07 12:44:36 +00001893// It loads 1 byte from each source of the memcmp parameters with the given
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001894// GEPIndex. It then subtracts the two loaded values and adds this result to the
1895// final phi node for selecting the memcmp result.
Clement Courbet0c7cd072017-10-25 11:02:09 +00001896void MemCmpExpansion::emitLoadCompareByteBlock(unsigned BlockIndex,
Sanjay Patela10f5b62017-06-21 18:06:13 +00001897 unsigned GEPIndex) {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001898 Value *Source1 = CI->getArgOperand(0);
1899 Value *Source2 = CI->getArgOperand(1);
1900
Clement Courbet0c7cd072017-10-25 11:02:09 +00001901 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001902 Type *LoadSizeType = Type::getInt8Ty(CI->getContext());
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001903 // Cast source to LoadSizeType*.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001904 if (Source1->getType() != LoadSizeType)
1905 Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1906 if (Source2->getType() != LoadSizeType)
1907 Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1908
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001909 // Get the base address using the GEPIndex.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001910 if (GEPIndex != 0) {
1911 Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1912 ConstantInt::get(LoadSizeType, GEPIndex));
1913 Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1914 ConstantInt::get(LoadSizeType, GEPIndex));
1915 }
1916
1917 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1918 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1919
1920 LoadSrc1 = Builder.CreateZExt(LoadSrc1, Type::getInt32Ty(CI->getContext()));
1921 LoadSrc2 = Builder.CreateZExt(LoadSrc2, Type::getInt32Ty(CI->getContext()));
1922 Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2);
1923
Clement Courbet0c7cd072017-10-25 11:02:09 +00001924 PhiRes->addIncoming(Diff, LoadCmpBlocks[BlockIndex]);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001925
Clement Courbet0c7cd072017-10-25 11:02:09 +00001926 if (BlockIndex < (LoadCmpBlocks.size() - 1)) {
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001927 // Early exit branch if difference found to EndBlock. Otherwise, continue to
1928 // next LoadCmpBlock,
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001929 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
1930 ConstantInt::get(Diff->getType(), 0));
1931 BranchInst *CmpBr =
Clement Courbet0c7cd072017-10-25 11:02:09 +00001932 BranchInst::Create(EndBlock, LoadCmpBlocks[BlockIndex + 1], Cmp);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001933 Builder.Insert(CmpBr);
1934 } else {
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001935 // The last block has an unconditional branch to EndBlock.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001936 BranchInst *CmpBr = BranchInst::Create(EndBlock);
1937 Builder.Insert(CmpBr);
1938 }
1939}
1940
Sanjay Patel60070002017-06-07 13:33:00 +00001941/// Generate an equality comparison for one or more pairs of loaded values.
1942/// This is used in the case where the memcmp() call is compared equal or not
1943/// equal to zero.
Clement Courbet0c7cd072017-10-25 11:02:09 +00001944Value *MemCmpExpansion::getCompareLoadPairs(unsigned BlockIndex,
1945 unsigned &LoadIndex) {
1946 assert(LoadIndex < getNumLoads() &&
1947 "getCompareLoadPairs() called with no remaining loads");
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001948 std::vector<Value *> XorList, OrList;
1949 Value *Diff;
1950
Clement Courbet0c7cd072017-10-25 11:02:09 +00001951 const unsigned NumLoads =
1952 std::min(getNumLoads() - LoadIndex, NumLoadsPerBlock);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001953
Sanjay Patele7c50412017-06-08 16:53:18 +00001954 // For a single-block expansion, start inserting before the memcmp call.
1955 if (LoadCmpBlocks.empty())
1956 Builder.SetInsertPoint(CI);
1957 else
Clement Courbet0c7cd072017-10-25 11:02:09 +00001958 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
Sanjay Patele7c50412017-06-08 16:53:18 +00001959
Sanjay Patelf57015d2017-06-07 00:17:08 +00001960 Value *Cmp = nullptr;
Clement Courbet0c7cd072017-10-25 11:02:09 +00001961 // If we have multiple loads per block, we need to generate a composite
1962 // comparison using xor+or. The type for the combinations is the largest load
1963 // type.
1964 IntegerType *const MaxLoadType =
1965 NumLoads == 1 ? nullptr
1966 : IntegerType::get(CI->getContext(), MaxLoadSize * 8);
1967 for (unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) {
1968 const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex];
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001969
Clement Courbet0c7cd072017-10-25 11:02:09 +00001970 IntegerType *LoadSizeType =
1971 IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001972
1973 Value *Source1 = CI->getArgOperand(0);
1974 Value *Source2 = CI->getArgOperand(1);
1975
Sanjay Patelb4b7df92017-06-06 20:30:47 +00001976 // Cast source to LoadSizeType*.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001977 if (Source1->getType() != LoadSizeType)
1978 Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1979 if (Source2->getType() != LoadSizeType)
1980 Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1981
Clement Courbet0c7cd072017-10-25 11:02:09 +00001982 // Get the base address using a GEP.
1983 if (CurLoadEntry.Offset != 0) {
1984 Source1 = Builder.CreateGEP(
1985 LoadSizeType, Source1,
1986 ConstantInt::get(LoadSizeType, CurLoadEntry.getGEPIndex()));
1987 Source2 = Builder.CreateGEP(
1988 LoadSizeType, Source2,
1989 ConstantInt::get(LoadSizeType, CurLoadEntry.getGEPIndex()));
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001990 }
1991
Sanjay Patela351a612017-06-19 19:48:35 +00001992 // Get a constant or load a value for each source address.
1993 Value *LoadSrc1 = nullptr;
1994 if (auto *Source1C = dyn_cast<Constant>(Source1))
1995 LoadSrc1 = ConstantFoldLoadFromConstPtr(Source1C, LoadSizeType, DL);
1996 if (!LoadSrc1)
1997 LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1998
1999 Value *LoadSrc2 = nullptr;
2000 if (auto *Source2C = dyn_cast<Constant>(Source2))
2001 LoadSrc2 = ConstantFoldLoadFromConstPtr(Source2C, LoadSizeType, DL);
2002 if (!LoadSrc2)
2003 LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
2004
Sanjay Patelf57015d2017-06-07 00:17:08 +00002005 if (NumLoads != 1) {
Sanjay Patel8ce1e3b2017-06-07 16:16:45 +00002006 if (LoadSizeType != MaxLoadType) {
Sanjay Patel2a6f9f82017-06-21 18:20:52 +00002007 LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType);
2008 LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType);
Sanjay Patel8ce1e3b2017-06-07 16:16:45 +00002009 }
Sanjay Patelf57015d2017-06-07 00:17:08 +00002010 // If we have multiple loads per block, we need to generate a composite
2011 // comparison using xor+or.
2012 Diff = Builder.CreateXor(LoadSrc1, LoadSrc2);
Sanjay Patel2a6f9f82017-06-21 18:20:52 +00002013 Diff = Builder.CreateZExt(Diff, MaxLoadType);
Sanjay Patelf57015d2017-06-07 00:17:08 +00002014 XorList.push_back(Diff);
2015 } else {
2016 // If there's only one load per block, we just compare the loaded values.
2017 Cmp = Builder.CreateICmpNE(LoadSrc1, LoadSrc2);
2018 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002019 }
2020
2021 auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
2022 std::vector<Value *> OutList;
2023 for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
2024 Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
2025 OutList.push_back(Or);
2026 }
2027 if (InList.size() % 2 != 0)
2028 OutList.push_back(InList.back());
2029 return OutList;
2030 };
2031
Sanjay Patelf57015d2017-06-07 00:17:08 +00002032 if (!Cmp) {
2033 // Pairwise OR the XOR results.
2034 OrList = pairWiseOr(XorList);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002035
Sanjay Patelf57015d2017-06-07 00:17:08 +00002036 // Pairwise OR the OR results until one result left.
2037 while (OrList.size() != 1) {
2038 OrList = pairWiseOr(OrList);
2039 }
2040 Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002041 }
2042
Sanjay Patel60070002017-06-07 13:33:00 +00002043 return Cmp;
2044}
2045
Clement Courbet0c7cd072017-10-25 11:02:09 +00002046void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
2047 unsigned &LoadIndex) {
2048 Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex);
Sanjay Patel60070002017-06-07 13:33:00 +00002049
Clement Courbet0c7cd072017-10-25 11:02:09 +00002050 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002051 ? EndBlock
Clement Courbet0c7cd072017-10-25 11:02:09 +00002052 : LoadCmpBlocks[BlockIndex + 1];
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002053 // Early exit branch if difference found to ResultBlock. Otherwise,
2054 // continue to next LoadCmpBlock or EndBlock.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002055 BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
2056 Builder.Insert(CmpBr);
2057
2058 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
2059 // since early exit to ResultBlock was not taken (no difference was found in
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002060 // any of the bytes).
Clement Courbet0c7cd072017-10-25 11:02:09 +00002061 if (BlockIndex == LoadCmpBlocks.size() - 1) {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002062 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
Clement Courbet0c7cd072017-10-25 11:02:09 +00002063 PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002064 }
2065}
2066
2067// This function creates the IR intructions for loading and comparing using the
2068// given LoadSize. It loads the number of bytes specified by LoadSize from each
2069// source of the memcmp parameters. It then does a subtract to see if there was
2070// a difference in the loaded values. If a difference is found, it branches
2071// with an early exit to the ResultBlock for calculating which source was
2072// larger. Otherwise, it falls through to the either the next LoadCmpBlock or
2073// the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
2074// a special case through emitLoadCompareByteBlock. The special handling can
2075// simply subtract the loaded values and add it to the result phi node.
Clement Courbet0c7cd072017-10-25 11:02:09 +00002076void MemCmpExpansion::emitLoadCompareBlock(unsigned BlockIndex) {
2077 // There is one load per block in this case, BlockIndex == LoadIndex.
2078 const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex];
2079
2080 if (CurLoadEntry.LoadSize == 1) {
2081 MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex,
2082 CurLoadEntry.getGEPIndex());
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002083 return;
2084 }
2085
Clement Courbet0c7cd072017-10-25 11:02:09 +00002086 Type *LoadSizeType =
2087 IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002088 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
Clement Courbet0c7cd072017-10-25 11:02:09 +00002089 assert(CurLoadEntry.LoadSize <= MaxLoadSize && "Unexpected load type");
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002090
2091 Value *Source1 = CI->getArgOperand(0);
2092 Value *Source2 = CI->getArgOperand(1);
2093
Clement Courbet0c7cd072017-10-25 11:02:09 +00002094 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002095 // Cast source to LoadSizeType*.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002096 if (Source1->getType() != LoadSizeType)
2097 Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
2098 if (Source2->getType() != LoadSizeType)
2099 Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
2100
Clement Courbet0c7cd072017-10-25 11:02:09 +00002101 // Get the base address using a GEP.
2102 if (CurLoadEntry.Offset != 0) {
2103 Source1 = Builder.CreateGEP(
2104 LoadSizeType, Source1,
2105 ConstantInt::get(LoadSizeType, CurLoadEntry.getGEPIndex()));
2106 Source2 = Builder.CreateGEP(
2107 LoadSizeType, Source2,
2108 ConstantInt::get(LoadSizeType, CurLoadEntry.getGEPIndex()));
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002109 }
2110
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002111 // Load LoadSizeType from the base address.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002112 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
2113 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
2114
Sanjay Patel2843cad2017-06-09 23:01:05 +00002115 if (DL.isLittleEndian()) {
Sanjay Patel352e6052017-06-27 19:31:35 +00002116 Function *Bswap = Intrinsic::getDeclaration(CI->getModule(),
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002117 Intrinsic::bswap, LoadSizeType);
2118 LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1);
2119 LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2);
2120 }
2121
2122 if (LoadSizeType != MaxLoadType) {
Sanjay Patel2a6f9f82017-06-21 18:20:52 +00002123 LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType);
2124 LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002125 }
2126
2127 // Add the loaded values to the phi nodes for calculating memcmp result only
2128 // if result is not used in a zero equality.
2129 if (!IsUsedForZeroCmp) {
Clement Courbet0c7cd072017-10-25 11:02:09 +00002130 ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[BlockIndex]);
2131 ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[BlockIndex]);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002132 }
2133
Sanjay Patel70b36f12017-06-27 21:46:34 +00002134 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, LoadSrc1, LoadSrc2);
Clement Courbet0c7cd072017-10-25 11:02:09 +00002135 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002136 ? EndBlock
Clement Courbet0c7cd072017-10-25 11:02:09 +00002137 : LoadCmpBlocks[BlockIndex + 1];
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002138 // Early exit branch if difference found to ResultBlock. Otherwise, continue
2139 // to next LoadCmpBlock or EndBlock.
Sanjay Patel70b36f12017-06-27 21:46:34 +00002140 BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002141 Builder.Insert(CmpBr);
2142
2143 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
2144 // since early exit to ResultBlock was not taken (no difference was found in
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002145 // any of the bytes).
Clement Courbet0c7cd072017-10-25 11:02:09 +00002146 if (BlockIndex == LoadCmpBlocks.size() - 1) {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002147 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
Clement Courbet0c7cd072017-10-25 11:02:09 +00002148 PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002149 }
2150}
2151
2152// This function populates the ResultBlock with a sequence to calculate the
2153// memcmp result. It compares the two loaded source values and returns -1 if
2154// src1 < src2 and 1 if src1 > src2.
Sanjay Patel2843cad2017-06-09 23:01:05 +00002155void MemCmpExpansion::emitMemCmpResultBlock() {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002156 // Special case: if memcmp result is used in a zero equality, result does not
2157 // need to be calculated and can simply return 1.
2158 if (IsUsedForZeroCmp) {
2159 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
2160 Builder.SetInsertPoint(ResBlock.BB, InsertPt);
2161 Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
2162 PhiRes->addIncoming(Res, ResBlock.BB);
2163 BranchInst *NewBr = BranchInst::Create(EndBlock);
2164 Builder.Insert(NewBr);
2165 return;
2166 }
2167 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
2168 Builder.SetInsertPoint(ResBlock.BB, InsertPt);
2169
2170 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
2171 ResBlock.PhiSrc2);
2172
2173 Value *Res =
2174 Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
2175 ConstantInt::get(Builder.getInt32Ty(), 1));
2176
2177 BranchInst *NewBr = BranchInst::Create(EndBlock);
2178 Builder.Insert(NewBr);
2179 PhiRes->addIncoming(Res, ResBlock.BB);
2180}
2181
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002182void MemCmpExpansion::setupResultBlockPHINodes() {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002183 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
2184 Builder.SetInsertPoint(ResBlock.BB);
Clement Courbet0c7cd072017-10-25 11:02:09 +00002185 // Note: this assumes one load per block.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002186 ResBlock.PhiSrc1 =
Clement Courbet0c7cd072017-10-25 11:02:09 +00002187 Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src1");
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002188 ResBlock.PhiSrc2 =
Clement Courbet0c7cd072017-10-25 11:02:09 +00002189 Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src2");
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002190}
2191
2192void MemCmpExpansion::setupEndBlockPHINodes() {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002193 Builder.SetInsertPoint(&EndBlock->front());
2194 PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
2195}
2196
Clement Courbet0c7cd072017-10-25 11:02:09 +00002197Value *MemCmpExpansion::getMemCmpExpansionZeroCase() {
2198 unsigned LoadIndex = 0;
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002199 // This loop populates each of the LoadCmpBlocks with the IR sequence to
2200 // handle multiple loads per block.
Clement Courbet0c7cd072017-10-25 11:02:09 +00002201 for (unsigned I = 0; I < getNumBlocks(); ++I) {
2202 emitLoadCompareBlockMultipleLoads(I, LoadIndex);
2203 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002204
Sanjay Patel2843cad2017-06-09 23:01:05 +00002205 emitMemCmpResultBlock();
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002206 return PhiRes;
2207}
2208
Sanjay Patele7c50412017-06-08 16:53:18 +00002209/// A memcmp expansion that compares equality with 0 and only has one block of
2210/// load and compare can bypass the compare, branch, and phi IR that is required
2211/// in the general case.
Clement Courbet0c7cd072017-10-25 11:02:09 +00002212Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() {
2213 unsigned LoadIndex = 0;
2214 Value *Cmp = getCompareLoadPairs(0, LoadIndex);
2215 assert(LoadIndex == getNumLoads() && "some entries were not consumed");
Sanjay Patele7c50412017-06-08 16:53:18 +00002216 return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
2217}
2218
Sanjay Patel4b23fa02017-06-27 23:15:01 +00002219/// A memcmp expansion that only has one block of load and compare can bypass
2220/// the compare, branch, and phi IR that is required in the general case.
Clement Courbet0c7cd072017-10-25 11:02:09 +00002221Value *MemCmpExpansion::getMemCmpOneBlock() {
Sanjay Patel4b23fa02017-06-27 23:15:01 +00002222 assert(NumLoadsPerBlock == 1 && "Only handles one load pair per block");
2223
2224 Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8);
2225 Value *Source1 = CI->getArgOperand(0);
2226 Value *Source2 = CI->getArgOperand(1);
2227
2228 // Cast source to LoadSizeType*.
2229 if (Source1->getType() != LoadSizeType)
2230 Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
2231 if (Source2->getType() != LoadSizeType)
2232 Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
2233
2234 // Load LoadSizeType from the base address.
2235 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
2236 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
2237
2238 if (DL.isLittleEndian() && Size != 1) {
2239 Function *Bswap = Intrinsic::getDeclaration(CI->getModule(),
2240 Intrinsic::bswap, LoadSizeType);
2241 LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1);
2242 LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2);
2243 }
2244
Sanjay Patelfea731a2017-07-31 18:08:24 +00002245 if (Size < 4) {
2246 // The i8 and i16 cases don't need compares. We zext the loaded values and
2247 // subtract them to get the suitable negative, zero, or positive i32 result.
2248 LoadSrc1 = Builder.CreateZExt(LoadSrc1, Builder.getInt32Ty());
2249 LoadSrc2 = Builder.CreateZExt(LoadSrc2, Builder.getInt32Ty());
2250 return Builder.CreateSub(LoadSrc1, LoadSrc2);
2251 }
2252
2253 // The result of memcmp is negative, zero, or positive, so produce that by
2254 // subtracting 2 extended compare bits: sub (ugt, ult).
2255 // If a target prefers to use selects to get -1/0/1, they should be able
2256 // to transform this later. The inverse transform (going from selects to math)
2257 // may not be possible in the DAG because the selects got converted into
2258 // branches before we got there.
2259 Value *CmpUGT = Builder.CreateICmpUGT(LoadSrc1, LoadSrc2);
Sanjay Patel4b23fa02017-06-27 23:15:01 +00002260 Value *CmpULT = Builder.CreateICmpULT(LoadSrc1, LoadSrc2);
Sanjay Patelfea731a2017-07-31 18:08:24 +00002261 Value *ZextUGT = Builder.CreateZExt(CmpUGT, Builder.getInt32Ty());
2262 Value *ZextULT = Builder.CreateZExt(CmpULT, Builder.getInt32Ty());
2263 return Builder.CreateSub(ZextUGT, ZextULT);
Sanjay Patel4b23fa02017-06-27 23:15:01 +00002264}
2265
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002266// This function expands the memcmp call into an inline expansion and returns
2267// the memcmp result.
Clement Courbet0c7cd072017-10-25 11:02:09 +00002268Value *MemCmpExpansion::getMemCmpExpansion() {
2269 computeLoadSequence();
2270 // A memcmp with zero-comparison with only one block of load and compare does
2271 // not need to set up any extra blocks. This case could be handled in the DAG,
2272 // but since we have all of the machinery to flexibly expand any memcpy here,
2273 // we choose to handle this case too to avoid fragmented lowering.
2274 if ((!IsUsedForZeroCmp && NumLoadsPerBlock != 1) || getNumBlocks() != 1) {
2275 BasicBlock *StartBlock = CI->getParent();
2276 EndBlock = StartBlock->splitBasicBlock(CI, "endblock");
2277 setupEndBlockPHINodes();
2278 createResultBlock();
2279
2280 // If return value of memcmp is not used in a zero equality, we need to
2281 // calculate which source was larger. The calculation requires the
2282 // two loaded source values of each load compare block.
2283 // These will be saved in the phi nodes created by setupResultBlockPHINodes.
2284 if (!IsUsedForZeroCmp) setupResultBlockPHINodes();
2285
2286 // Create the number of required load compare basic blocks.
2287 createLoadCmpBlocks();
2288
2289 // Update the terminator added by splitBasicBlock to branch to the first
2290 // LoadCmpBlock.
2291 StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
2292 }
2293
2294 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2295
Sanjay Patelab0ecc02017-06-07 12:44:36 +00002296 if (IsUsedForZeroCmp)
Clement Courbet0c7cd072017-10-25 11:02:09 +00002297 return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock()
2298 : getMemCmpExpansionZeroCase();
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002299
Sanjay Patel4b23fa02017-06-27 23:15:01 +00002300 // TODO: Handle more than one load pair per block in getMemCmpOneBlock().
Clement Courbet0c7cd072017-10-25 11:02:09 +00002301 if (getNumBlocks() == 1 && NumLoadsPerBlock == 1) return getMemCmpOneBlock();
Sanjay Patel4b23fa02017-06-27 23:15:01 +00002302
Clement Courbet0c7cd072017-10-25 11:02:09 +00002303 for (unsigned I = 0; I < getNumBlocks(); ++I) {
2304 emitLoadCompareBlock(I);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002305 }
2306
Sanjay Patel2843cad2017-06-09 23:01:05 +00002307 emitMemCmpResultBlock();
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002308 return PhiRes;
2309}
2310
2311// This function checks to see if an expansion of memcmp can be generated.
2312// It checks for constant compare size that is less than the max inline size.
2313// If an expansion cannot occur, returns false to leave as a library call.
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002314// Otherwise, the library call is replaced with a new IR instruction sequence.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002315/// We want to transform:
2316/// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
2317/// To:
2318/// loadbb:
2319/// %0 = bitcast i32* %buffer2 to i8*
2320/// %1 = bitcast i32* %buffer1 to i8*
2321/// %2 = bitcast i8* %1 to i64*
2322/// %3 = bitcast i8* %0 to i64*
2323/// %4 = load i64, i64* %2
2324/// %5 = load i64, i64* %3
2325/// %6 = call i64 @llvm.bswap.i64(i64 %4)
2326/// %7 = call i64 @llvm.bswap.i64(i64 %5)
2327/// %8 = sub i64 %6, %7
2328/// %9 = icmp ne i64 %8, 0
2329/// br i1 %9, label %res_block, label %loadbb1
2330/// res_block: ; preds = %loadbb2,
2331/// %loadbb1, %loadbb
2332/// %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
2333/// %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
2334/// %10 = icmp ult i64 %phi.src1, %phi.src2
2335/// %11 = select i1 %10, i32 -1, i32 1
2336/// br label %endblock
2337/// loadbb1: ; preds = %loadbb
2338/// %12 = bitcast i32* %buffer2 to i8*
2339/// %13 = bitcast i32* %buffer1 to i8*
2340/// %14 = bitcast i8* %13 to i32*
2341/// %15 = bitcast i8* %12 to i32*
2342/// %16 = getelementptr i32, i32* %14, i32 2
2343/// %17 = getelementptr i32, i32* %15, i32 2
2344/// %18 = load i32, i32* %16
2345/// %19 = load i32, i32* %17
2346/// %20 = call i32 @llvm.bswap.i32(i32 %18)
2347/// %21 = call i32 @llvm.bswap.i32(i32 %19)
2348/// %22 = zext i32 %20 to i64
2349/// %23 = zext i32 %21 to i64
2350/// %24 = sub i64 %22, %23
2351/// %25 = icmp ne i64 %24, 0
2352/// br i1 %25, label %res_block, label %loadbb2
2353/// loadbb2: ; preds = %loadbb1
2354/// %26 = bitcast i32* %buffer2 to i8*
2355/// %27 = bitcast i32* %buffer1 to i8*
2356/// %28 = bitcast i8* %27 to i16*
2357/// %29 = bitcast i8* %26 to i16*
2358/// %30 = getelementptr i16, i16* %28, i16 6
2359/// %31 = getelementptr i16, i16* %29, i16 6
2360/// %32 = load i16, i16* %30
2361/// %33 = load i16, i16* %31
2362/// %34 = call i16 @llvm.bswap.i16(i16 %32)
2363/// %35 = call i16 @llvm.bswap.i16(i16 %33)
2364/// %36 = zext i16 %34 to i64
2365/// %37 = zext i16 %35 to i64
2366/// %38 = sub i64 %36, %37
2367/// %39 = icmp ne i64 %38, 0
2368/// br i1 %39, label %res_block, label %loadbb3
2369/// loadbb3: ; preds = %loadbb2
2370/// %40 = bitcast i32* %buffer2 to i8*
2371/// %41 = bitcast i32* %buffer1 to i8*
2372/// %42 = getelementptr i8, i8* %41, i8 14
2373/// %43 = getelementptr i8, i8* %40, i8 14
2374/// %44 = load i8, i8* %42
2375/// %45 = load i8, i8* %43
2376/// %46 = zext i8 %44 to i32
2377/// %47 = zext i8 %45 to i32
2378/// %48 = sub i32 %46, %47
2379/// br label %endblock
2380/// endblock: ; preds = %res_block,
2381/// %loadbb3
2382/// %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
2383/// ret i32 %phi.res
2384static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
2385 const TargetLowering *TLI, const DataLayout *DL) {
2386 NumMemCmpCalls++;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002387
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002388 // Early exit from expansion if -Oz.
Sanjay Patel4137d512017-06-07 14:29:52 +00002389 if (CI->getFunction()->optForMinSize())
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002390 return false;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002391
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002392 // Early exit from expansion if size is not a constant.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002393 ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2394 if (!SizeCast) {
2395 NumMemCmpNotConstant++;
2396 return false;
2397 }
Clement Courbet0c7cd072017-10-25 11:02:09 +00002398 const uint64_t SizeVal = SizeCast->getZExtValue();
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002399
Clement Courbet0c7cd072017-10-25 11:02:09 +00002400 // TTI call to check if target would like to expand memcmp. Also, get the
2401 // max LoadSize.
2402 unsigned MaxLoadSize;
2403 if (!TTI->enableMemCmpExpansion(MaxLoadSize)) return false;
Sanjay Patel4dbdd472017-08-01 17:24:54 +00002404
Clement Courbet0c7cd072017-10-25 11:02:09 +00002405 MemCmpExpansion Expansion(CI, SizeVal, MaxLoadSize, MemCmpNumLoadsPerBlock,
2406 *DL);
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002407
Sanjay Patel4dbdd472017-08-01 17:24:54 +00002408 // Don't expand if this will require more loads than desired by the target.
Clement Courbet0c7cd072017-10-25 11:02:09 +00002409 if (Expansion.getNumLoads() >
2410 TLI->getMaxExpandSizeMemcmp(CI->getFunction()->optForSize())) {
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002411 NumMemCmpGreaterThanMax++;
2412 return false;
2413 }
2414
2415 NumMemCmpInlined++;
2416
Clement Courbet0c7cd072017-10-25 11:02:09 +00002417 Value *Res = Expansion.getMemCmpExpansion();
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002418
Sanjay Patelb4b7df92017-06-06 20:30:47 +00002419 // Replace call with result of expansion and erase call.
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002420 CI->replaceAllUsesWith(Res);
2421 CI->eraseFromParent();
2422
2423 return true;
2424}
2425
Sanjay Patel3b8974b2017-06-08 20:00:09 +00002426bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00002427 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002428
Chris Lattner7a277142011-01-15 07:14:54 +00002429 // Lower inline assembly if we can.
2430 // If we found an inline asm expession, and if the target knows how to
2431 // lower it to normal LLVM code, do so now.
2432 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2433 if (TLI->ExpandInlineAsm(CI)) {
2434 // Avoid invalidating the iterator.
2435 CurInstIterator = BB->begin();
2436 // Avoid processing instructions out of order, which could cause
2437 // reuse before a value is defined.
2438 SunkAddrs.clear();
2439 return true;
2440 }
2441 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002442 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00002443 return true;
2444 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002445
John Brawn0dbcd652015-03-18 12:01:59 +00002446 // Align the pointer arguments to this call if the target thinks it's a good
2447 // idea
2448 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002449 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00002450 for (auto &Arg : CI->arg_operands()) {
2451 // We want to align both objects whose address is used directly and
2452 // objects whose address is used in casts and GEPs, though it only makes
2453 // sense for GEPs if the offset is a multiple of the desired alignment and
2454 // if size - offset meets the size threshold.
2455 if (!Arg->getType()->isPointerTy())
2456 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002457 APInt Offset(DL->getPointerSizeInBits(
2458 cast<PointerType>(Arg->getType())->getAddressSpace()),
2459 0);
2460 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00002461 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00002462 if ((Offset2 & (PrefAlign-1)) != 0)
2463 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00002464 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002465 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2466 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00002467 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00002468 // Global variables can only be aligned if they are defined in this
2469 // object (i.e. they are uniquely initialized in this object), and
2470 // over-aligning global variables that have an explicit section is
2471 // forbidden.
2472 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00002473 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00002474 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002475 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00002476 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00002477 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00002478 }
2479 // If this is a memcpy (or similar) then we may be able to improve the
2480 // alignment
2481 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002482 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00002483 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00002484 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002485 if (Align > MI->getAlignment())
2486 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00002487 }
2488 }
2489
Philip Reamesac115ed2016-03-09 23:13:12 +00002490 // If we have a cold call site, try to sink addressing computation into the
2491 // cold block. This interacts with our handling for loads and stores to
2492 // ensure that we can fold all uses of a potential addressing computation
2493 // into their uses. TODO: generalize this to work over profiling data
2494 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
2495 for (auto &Arg : CI->arg_operands()) {
2496 if (!Arg->getType()->isPointerTy())
2497 continue;
2498 unsigned AS = Arg->getType()->getPointerAddressSpace();
2499 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2500 }
Junmo Park6098cbb2016-03-11 07:05:32 +00002501
Eric Christopher4b7948e2010-03-11 02:41:03 +00002502 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002503 if (II) {
2504 switch (II->getIntrinsicID()) {
2505 default: break;
2506 case Intrinsic::objectsize: {
2507 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00002508 ConstantInt *RetVal =
2509 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002510 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00002511 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
2512 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00002513 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002514 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00002515 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00002516
Sanjay Patel545a4562016-01-20 18:59:16 +00002517 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00002518
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002519 // If the iterator instruction was recursively deleted, start over at the
2520 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002521 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002522 CurInstIterator = BB->begin();
2523 SunkAddrs.clear();
2524 }
2525 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00002526 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002527 case Intrinsic::aarch64_stlxr:
2528 case Intrinsic::aarch64_stxr: {
2529 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2530 if (!ExtVal || !ExtVal->hasOneUse() ||
2531 ExtVal->getParent() == CI->getParent())
2532 return false;
2533 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2534 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002535 // Mark this instruction as "inserted by CGP", so that other
2536 // optimizations don't touch it.
2537 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002538 return true;
2539 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002540 case Intrinsic::invariant_group_barrier:
2541 II->replaceAllUsesWith(II->getArgOperand(0));
2542 II->eraseFromParent();
2543 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002544
2545 case Intrinsic::cttz:
2546 case Intrinsic::ctlz:
2547 // If counting zeros is expensive, try to avoid it.
2548 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002549 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002550
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002551 if (TLI) {
2552 SmallVector<Value*, 2> PtrOps;
2553 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002554 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2555 while (!PtrOps.empty()) {
2556 Value *PtrVal = PtrOps.pop_back_val();
2557 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2558 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002559 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002560 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002561 }
Pete Cooper615fd892012-03-13 20:59:56 +00002562 }
2563
Eric Christopher4b7948e2010-03-11 02:41:03 +00002564 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002565 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002566
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002567 // Lower all default uses of _chk calls. This is very similar
2568 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002569 // to fortified library functions (e.g. __memcpy_chk) that have the default
2570 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002571 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002572 if (Value *V = Simplifier.optimizeCall(CI)) {
2573 CI->replaceAllUsesWith(V);
2574 CI->eraseFromParent();
2575 return true;
2576 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002577
2578 LibFunc Func;
Sanjay Patel5e370852017-06-08 19:47:25 +00002579 if (TLInfo->getLibFunc(ImmutableCallSite(CI), Func) &&
2580 Func == LibFunc_memcmp && expandMemCmp(CI, TTI, TLI, DL)) {
2581 ModifiedDT = true;
2582 return true;
Zaara Syeda3a7578c2017-05-31 17:12:38 +00002583 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002584 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002585}
Chris Lattner1b93be52011-01-15 07:25:29 +00002586
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002587/// Look for opportunities to duplicate return instructions to the predecessor
2588/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002589/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002590/// bb0:
2591/// %tmp0 = tail call i32 @f0()
2592/// br label %return
2593/// bb1:
2594/// %tmp1 = tail call i32 @f1()
2595/// br label %return
2596/// bb2:
2597/// %tmp2 = tail call i32 @f2()
2598/// br label %return
2599/// return:
2600/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2601/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002602/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002603///
2604/// =>
2605///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002606/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002607/// bb0:
2608/// %tmp0 = tail call i32 @f0()
2609/// ret i32 %tmp0
2610/// bb1:
2611/// %tmp1 = tail call i32 @f1()
2612/// ret i32 %tmp1
2613/// bb2:
2614/// %tmp2 = tail call i32 @f2()
2615/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002616/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002617bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002618 if (!TLI)
2619 return false;
2620
Michael Kuperstein71321562016-09-07 20:29:49 +00002621 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2622 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002623 return false;
2624
Craig Topperc0196b12014-04-14 00:51:57 +00002625 PHINode *PN = nullptr;
2626 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002627 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002628 if (V) {
2629 BCI = dyn_cast<BitCastInst>(V);
2630 if (BCI)
2631 V = BCI->getOperand(0);
2632
2633 PN = dyn_cast<PHINode>(V);
2634 if (!PN)
2635 return false;
2636 }
Evan Cheng0663f232011-03-21 01:19:09 +00002637
Cameron Zwarich4649f172011-03-24 04:52:10 +00002638 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002639 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002640
Cameron Zwarich4649f172011-03-24 04:52:10 +00002641 // Make sure there are no instructions between the PHI and return, or that the
2642 // return is the first instruction in the block.
2643 if (PN) {
2644 BasicBlock::iterator BI = BB->begin();
2645 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002646 if (&*BI == BCI)
2647 // Also skip over the bitcast.
2648 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002649 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002650 return false;
2651 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002652 BasicBlock::iterator BI = BB->begin();
2653 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002654 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002655 return false;
2656 }
Evan Cheng0663f232011-03-21 01:19:09 +00002657
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002658 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2659 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002660 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002661 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002662 if (PN) {
2663 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2664 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2665 // Make sure the phi value is indeed produced by the tail call.
2666 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002667 TLI->mayBeEmittedAsTailCall(CI) &&
2668 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002669 TailCalls.push_back(CI);
2670 }
2671 } else {
2672 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002673 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002674 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002675 continue;
2676
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002677 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002678 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2679 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002680 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2681 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002682 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002683
Cameron Zwarich4649f172011-03-24 04:52:10 +00002684 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002685 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2686 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002687 TailCalls.push_back(CI);
2688 }
Evan Cheng0663f232011-03-21 01:19:09 +00002689 }
2690
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002691 bool Changed = false;
2692 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2693 CallInst *CI = TailCalls[i];
2694 CallSite CS(CI);
2695
2696 // Conservatively require the attributes of the call to match those of the
2697 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00002698 AttributeList CalleeAttrs = CS.getAttributes();
2699 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2700 .removeAttribute(Attribute::NoAlias) !=
2701 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2702 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002703 continue;
2704
2705 // Make sure the call instruction is followed by an unconditional branch to
2706 // the return block.
2707 BasicBlock *CallBB = CI->getParent();
2708 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2709 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2710 continue;
2711
2712 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002713 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002714 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002715 ++NumRetsDup;
2716 }
2717
2718 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002719 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002720 BB->eraseFromParent();
2721
2722 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002723}
2724
Chris Lattner728f9022008-11-25 07:09:13 +00002725//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002726// Memory Optimization
2727//===----------------------------------------------------------------------===//
2728
Chandler Carruthc8925912013-01-05 02:09:22 +00002729namespace {
2730
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002731/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002732/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002733struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002734 Value *BaseReg = nullptr;
2735 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00002736 Value *OriginalValue = nullptr;
2737
2738 enum FieldName {
2739 NoField = 0x00,
2740 BaseRegField = 0x01,
2741 BaseGVField = 0x02,
2742 BaseOffsField = 0x04,
2743 ScaledRegField = 0x08,
2744 ScaleField = 0x10,
2745 MultipleFields = 0xff
2746 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00002747
2748 ExtAddrMode() = default;
2749
Chandler Carruthc8925912013-01-05 02:09:22 +00002750 void print(raw_ostream &OS) const;
2751 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002752
John Brawn736bf002017-10-03 13:08:22 +00002753 FieldName compare(const ExtAddrMode &other) {
2754 // First check that the types are the same on each field, as differing types
2755 // is something we can't cope with later on.
2756 if (BaseReg && other.BaseReg &&
2757 BaseReg->getType() != other.BaseReg->getType())
2758 return MultipleFields;
2759 if (BaseGV && other.BaseGV &&
2760 BaseGV->getType() != other.BaseGV->getType())
2761 return MultipleFields;
2762 if (ScaledReg && other.ScaledReg &&
2763 ScaledReg->getType() != other.ScaledReg->getType())
2764 return MultipleFields;
2765
2766 // Check each field to see if it differs.
2767 unsigned Result = NoField;
2768 if (BaseReg != other.BaseReg)
2769 Result |= BaseRegField;
2770 if (BaseGV != other.BaseGV)
2771 Result |= BaseGVField;
2772 if (BaseOffs != other.BaseOffs)
2773 Result |= BaseOffsField;
2774 if (ScaledReg != other.ScaledReg)
2775 Result |= ScaledRegField;
2776 // Don't count 0 as being a different scale, because that actually means
2777 // unscaled (which will already be counted by having no ScaledReg).
2778 if (Scale && other.Scale && Scale != other.Scale)
2779 Result |= ScaleField;
2780
2781 if (countPopulation(Result) > 1)
2782 return MultipleFields;
2783 else
2784 return static_cast<FieldName>(Result);
2785 }
2786
2787 // AddrModes with a base reg or gv where the reg/gv is just the original
2788 // value are trivial.
2789 bool isTrivial() {
2790 bool Trivial = (BaseGV && BaseGV == OriginalValue) ||
2791 (BaseReg && BaseReg == OriginalValue);
2792 // If the AddrMode is trivial it shouldn't have an offset or be scaled.
2793 if (Trivial) {
2794 assert(BaseOffs == 0);
2795 assert(Scale == 0);
2796 }
2797 return Trivial;
Chandler Carruthc8925912013-01-05 02:09:22 +00002798 }
2799};
2800
Eugene Zelenko900b6332017-08-29 22:32:07 +00002801} // end anonymous namespace
2802
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002803#ifndef NDEBUG
2804static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2805 AM.print(OS);
2806 return OS;
2807}
2808#endif
2809
Aaron Ballman615eb472017-10-15 14:32:27 +00002810#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002811void ExtAddrMode::print(raw_ostream &OS) const {
2812 bool NeedPlus = false;
2813 OS << "[";
2814 if (BaseGV) {
2815 OS << (NeedPlus ? " + " : "")
2816 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002817 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002818 NeedPlus = true;
2819 }
2820
Richard Trieuc0f91212014-05-30 03:15:17 +00002821 if (BaseOffs) {
2822 OS << (NeedPlus ? " + " : "")
2823 << BaseOffs;
2824 NeedPlus = true;
2825 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002826
2827 if (BaseReg) {
2828 OS << (NeedPlus ? " + " : "")
2829 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002830 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002831 NeedPlus = true;
2832 }
2833 if (Scale) {
2834 OS << (NeedPlus ? " + " : "")
2835 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002836 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002837 }
2838
2839 OS << ']';
2840}
2841
Yaron Kereneb2a2542016-01-29 20:50:44 +00002842LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002843 print(dbgs());
2844 dbgs() << '\n';
2845}
2846#endif
2847
Eugene Zelenko900b6332017-08-29 22:32:07 +00002848namespace {
2849
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002850/// \brief This class provides transaction based operation on the IR.
2851/// Every change made through this class is recorded in the internal state and
2852/// can be undone (rollback) until commit is called.
2853class TypePromotionTransaction {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002854 /// \brief This represents the common interface of the individual transaction.
2855 /// Each class implements the logic for doing one specific modification on
2856 /// the IR via the TypePromotionTransaction.
2857 class TypePromotionAction {
2858 protected:
2859 /// The Instruction modified.
2860 Instruction *Inst;
2861
2862 public:
2863 /// \brief Constructor of the action.
2864 /// The constructor performs the related action on the IR.
2865 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2866
Eugene Zelenko900b6332017-08-29 22:32:07 +00002867 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002868
2869 /// \brief Undo the modification done by this action.
2870 /// When this method is called, the IR must be in the same state as it was
2871 /// before this action was applied.
2872 /// \pre Undoing the action works if and only if the IR is in the exact same
2873 /// state as it was directly after this action was applied.
2874 virtual void undo() = 0;
2875
2876 /// \brief Advocate every change made by this action.
2877 /// When the results on the IR of the action are to be kept, it is important
2878 /// to call this function, otherwise hidden information may be kept forever.
2879 virtual void commit() {
2880 // Nothing to be done, this action is not doing anything.
2881 }
2882 };
2883
2884 /// \brief Utility to remember the position of an instruction.
2885 class InsertionHandler {
2886 /// Position of an instruction.
2887 /// Either an instruction:
2888 /// - Is the first in a basic block: BB is used.
2889 /// - Has a previous instructon: PrevInst is used.
2890 union {
2891 Instruction *PrevInst;
2892 BasicBlock *BB;
2893 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002894
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002895 /// Remember whether or not the instruction had a previous instruction.
2896 bool HasPrevInstruction;
2897
2898 public:
2899 /// \brief Record the position of \p Inst.
2900 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002901 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002902 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2903 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002904 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002905 else
2906 Point.BB = Inst->getParent();
2907 }
2908
2909 /// \brief Insert \p Inst at the recorded position.
2910 void insert(Instruction *Inst) {
2911 if (HasPrevInstruction) {
2912 if (Inst->getParent())
2913 Inst->removeFromParent();
2914 Inst->insertAfter(Point.PrevInst);
2915 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002916 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002917 if (Inst->getParent())
2918 Inst->moveBefore(Position);
2919 else
2920 Inst->insertBefore(Position);
2921 }
2922 }
2923 };
2924
2925 /// \brief Move an instruction before another.
2926 class InstructionMoveBefore : public TypePromotionAction {
2927 /// Original position of the instruction.
2928 InsertionHandler Position;
2929
2930 public:
2931 /// \brief Move \p Inst before \p Before.
2932 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2933 : TypePromotionAction(Inst), Position(Inst) {
2934 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2935 Inst->moveBefore(Before);
2936 }
2937
2938 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002939 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002940 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2941 Position.insert(Inst);
2942 }
2943 };
2944
2945 /// \brief Set the operand of an instruction with a new value.
2946 class OperandSetter : public TypePromotionAction {
2947 /// Original operand of the instruction.
2948 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002949
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002950 /// Index of the modified instruction.
2951 unsigned Idx;
2952
2953 public:
2954 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2955 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2956 : TypePromotionAction(Inst), Idx(Idx) {
2957 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2958 << "for:" << *Inst << "\n"
2959 << "with:" << *NewVal << "\n");
2960 Origin = Inst->getOperand(Idx);
2961 Inst->setOperand(Idx, NewVal);
2962 }
2963
2964 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002965 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002966 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2967 << "for: " << *Inst << "\n"
2968 << "with: " << *Origin << "\n");
2969 Inst->setOperand(Idx, Origin);
2970 }
2971 };
2972
2973 /// \brief Hide the operands of an instruction.
2974 /// Do as if this instruction was not using any of its operands.
2975 class OperandsHider : public TypePromotionAction {
2976 /// The list of original operands.
2977 SmallVector<Value *, 4> OriginalValues;
2978
2979 public:
2980 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2981 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2982 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2983 unsigned NumOpnds = Inst->getNumOperands();
2984 OriginalValues.reserve(NumOpnds);
2985 for (unsigned It = 0; It < NumOpnds; ++It) {
2986 // Save the current operand.
2987 Value *Val = Inst->getOperand(It);
2988 OriginalValues.push_back(Val);
2989 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002990 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002991 // that we are not willing to pay.
2992 Inst->setOperand(It, UndefValue::get(Val->getType()));
2993 }
2994 }
2995
2996 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002997 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002998 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2999 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3000 Inst->setOperand(It, OriginalValues[It]);
3001 }
3002 };
3003
3004 /// \brief Build a truncate instruction.
3005 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00003006 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003007
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003008 public:
3009 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
3010 /// result.
3011 /// trunc Opnd to Ty.
3012 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3013 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003014 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3015 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003016 }
3017
Quentin Colombetac55b152014-09-16 22:36:07 +00003018 /// \brief Get the built value.
3019 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003020
3021 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00003022 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00003023 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3024 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3025 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003026 }
3027 };
3028
3029 /// \brief Build a sign extension instruction.
3030 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00003031 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003032
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003033 public:
3034 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
3035 /// result.
3036 /// sext Opnd to Ty.
3037 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00003038 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003039 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003040 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3041 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003042 }
3043
Quentin Colombetac55b152014-09-16 22:36:07 +00003044 /// \brief Get the built value.
3045 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003046
3047 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00003048 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00003049 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3050 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3051 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003052 }
3053 };
3054
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003055 /// \brief Build a zero extension instruction.
3056 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00003057 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003058
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003059 public:
3060 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
3061 /// result.
3062 /// zext Opnd to Ty.
3063 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00003064 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003065 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003066 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3067 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003068 }
3069
Quentin Colombetac55b152014-09-16 22:36:07 +00003070 /// \brief Get the built value.
3071 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003072
3073 /// \brief Remove the built instruction.
3074 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00003075 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3076 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3077 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003078 }
3079 };
3080
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003081 /// \brief Mutate an instruction to another type.
3082 class TypeMutator : public TypePromotionAction {
3083 /// Record the original type.
3084 Type *OrigTy;
3085
3086 public:
3087 /// \brief Mutate the type of \p Inst into \p NewTy.
3088 TypeMutator(Instruction *Inst, Type *NewTy)
3089 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3090 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3091 << "\n");
3092 Inst->mutateType(NewTy);
3093 }
3094
3095 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00003096 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003097 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3098 << "\n");
3099 Inst->mutateType(OrigTy);
3100 }
3101 };
3102
3103 /// \brief Replace the uses of an instruction by another instruction.
3104 class UsesReplacer : public TypePromotionAction {
3105 /// Helper structure to keep track of the replaced uses.
3106 struct InstructionAndIdx {
3107 /// The instruction using the instruction.
3108 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003109
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003110 /// The index where this instruction is used for Inst.
3111 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003112
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003113 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3114 : Inst(Inst), Idx(Idx) {}
3115 };
3116
3117 /// Keep track of the original uses (pair Instruction, Index).
3118 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003119
3120 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003121
3122 public:
3123 /// \brief Replace all the use of \p Inst by \p New.
3124 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
3125 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3126 << "\n");
3127 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003128 for (Use &U : Inst->uses()) {
3129 Instruction *UserI = cast<Instruction>(U.getUser());
3130 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003131 }
3132 // Now, we can replace the uses.
3133 Inst->replaceAllUsesWith(New);
3134 }
3135
3136 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00003137 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003138 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3139 for (use_iterator UseIt = OriginalUses.begin(),
3140 EndIt = OriginalUses.end();
3141 UseIt != EndIt; ++UseIt) {
3142 UseIt->Inst->setOperand(UseIt->Idx, Inst);
3143 }
3144 }
3145 };
3146
3147 /// \brief Remove an instruction from the IR.
3148 class InstructionRemover : public TypePromotionAction {
3149 /// Original position of the instruction.
3150 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003151
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003152 /// Helper structure to hide all the link to the instruction. In other
3153 /// words, this helps to do as if the instruction was removed.
3154 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003155
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003156 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003157 UsesReplacer *Replacer = nullptr;
3158
Jun Bum Limdee55652017-04-03 19:20:07 +00003159 /// Keep track of instructions removed.
3160 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003161
3162 public:
3163 /// \brief Remove all reference of \p Inst and optinally replace all its
3164 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00003165 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00003166 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00003167 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3168 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003169 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00003170 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003171 if (New)
3172 Replacer = new UsesReplacer(Inst, New);
3173 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00003174 RemovedInsts.insert(Inst);
3175 /// The instructions removed here will be freed after completing
3176 /// optimizeBlock() for all blocks as we need to keep track of the
3177 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003178 Inst->removeFromParent();
3179 }
3180
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00003181 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003182
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003183 /// \brief Resurrect the instruction and reassign it to the proper uses if
3184 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00003185 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003186 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3187 Inserter.insert(Inst);
3188 if (Replacer)
3189 Replacer->undo();
3190 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00003191 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003192 }
3193 };
3194
3195public:
3196 /// Restoration point.
3197 /// The restoration point is a pointer to an action instead of an iterator
3198 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003199 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00003200
3201 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3202 : RemovedInsts(RemovedInsts) {}
3203
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003204 /// Advocate every changes made in that transaction.
3205 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00003206
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003207 /// Undo all the changes made after the given point.
3208 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00003209
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003210 /// Get the current restoration point.
3211 ConstRestorationPt getRestorationPoint() const;
3212
3213 /// \name API for IR modification with state keeping to support rollback.
3214 /// @{
3215 /// Same as Instruction::setOperand.
3216 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00003217
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003218 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00003219 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00003220
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003221 /// Same as Value::replaceAllUsesWith.
3222 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00003223
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003224 /// Same as Value::mutateType.
3225 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00003226
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003227 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00003228 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00003229
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003230 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00003231 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00003232
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003233 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00003234 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00003235
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003236 /// Same as Instruction::moveBefore.
3237 void moveBefore(Instruction *Inst, Instruction *Before);
3238 /// @}
3239
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003240private:
3241 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00003242 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003243
3244 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3245
Jun Bum Limdee55652017-04-03 19:20:07 +00003246 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003247};
3248
Eugene Zelenko900b6332017-08-29 22:32:07 +00003249} // end anonymous namespace
3250
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003251void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3252 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00003253 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
3254 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003255}
3256
3257void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3258 Value *NewVal) {
3259 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003260 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
3261 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003262}
3263
3264void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3265 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00003266 Actions.push_back(
3267 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003268}
3269
3270void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00003271 Actions.push_back(
3272 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003273}
3274
Quentin Colombetac55b152014-09-16 22:36:07 +00003275Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3276 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00003277 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00003278 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00003279 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00003280 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003281}
3282
Quentin Colombetac55b152014-09-16 22:36:07 +00003283Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3284 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00003285 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00003286 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00003287 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00003288 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003289}
3290
Quentin Colombetac55b152014-09-16 22:36:07 +00003291Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3292 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003293 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00003294 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003295 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00003296 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003297}
3298
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003299void TypePromotionTransaction::moveBefore(Instruction *Inst,
3300 Instruction *Before) {
3301 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003302 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
3303 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003304}
3305
3306TypePromotionTransaction::ConstRestorationPt
3307TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00003308 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003309}
3310
3311void TypePromotionTransaction::commit() {
3312 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00003313 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003314 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003315 Actions.clear();
3316}
3317
3318void TypePromotionTransaction::rollback(
3319 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00003320 while (!Actions.empty() && Point != Actions.back().get()) {
3321 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003322 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003323 }
3324}
3325
Eugene Zelenko900b6332017-08-29 22:32:07 +00003326namespace {
3327
Chandler Carruthc8925912013-01-05 02:09:22 +00003328/// \brief A helper class for matching addressing modes.
3329///
3330/// This encapsulates the logic for matching the target-legal addressing modes.
3331class AddressingModeMatcher {
3332 SmallVectorImpl<Instruction*> &AddrModeInsts;
3333 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003334 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00003335 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00003336
3337 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3338 /// the memory instruction that we're computing this address for.
3339 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003340 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00003341 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00003342
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003343 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00003344 /// part of the return value of this addressing mode matching stuff.
3345 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003346
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003347 /// The instructions inserted by other CodeGenPrepare optimizations.
3348 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003349
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003350 /// A map from the instructions to their type before promotion.
3351 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00003352
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003353 /// The ongoing transaction where every action should be registered.
3354 TypePromotionTransaction &TPT;
3355
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003356 /// This is set to true when we should not do profitability checks.
3357 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003358 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00003359
Eric Christopherd75c00c2015-02-26 22:38:34 +00003360 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003361 const TargetLowering &TLI,
3362 const TargetRegisterInfo &TRI,
3363 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003364 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003365 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003366 InstrToOrigTy &PromotedInsts,
3367 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003368 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00003369 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3370 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3371 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003372 IgnoreProfitability = false;
3373 }
Stephen Lin837bba12013-07-15 17:55:02 +00003374
Eugene Zelenko900b6332017-08-29 22:32:07 +00003375public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003376 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00003377 /// give an access type of AccessTy. This returns a list of involved
3378 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003379 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003380 /// optimizations.
3381 /// \p PromotedInsts maps the instructions to their type before promotion.
3382 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003383 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00003384 Instruction *MemoryInst,
3385 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003386 const TargetLowering &TLI,
3387 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003388 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003389 InstrToOrigTy &PromotedInsts,
3390 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003391 ExtAddrMode Result;
3392
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003393 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
3394 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003395 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00003396 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003397 (void)Success; assert(Success && "Couldn't select *anything*?");
3398 return Result;
3399 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00003400
Chandler Carruthc8925912013-01-05 02:09:22 +00003401private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00003402 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3403 bool matchAddr(Value *V, unsigned Depth);
3404 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00003405 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003406 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00003407 ExtAddrMode &AMBefore,
3408 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003409 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3410 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00003411 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00003412};
3413
John Brawn736bf002017-10-03 13:08:22 +00003414/// \brief A helper class for combining addressing modes.
3415class AddressingModeCombiner {
3416private:
3417 /// The addressing modes we've collected.
3418 SmallVector<ExtAddrMode, 16> AddrModes;
3419
3420 /// The field in which the AddrModes differ, when we have more than one.
3421 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3422
3423 /// Are the AddrModes that we have all just equal to their original values?
3424 bool AllAddrModesTrivial = true;
3425
3426public:
3427 /// \brief Get the combined AddrMode
3428 const ExtAddrMode &getAddrMode() const {
3429 return AddrModes[0];
3430 }
3431
3432 /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
3433 /// have.
3434 /// \return True iff we succeeded in doing so.
3435 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3436 // Take note of if we have any non-trivial AddrModes, as we need to detect
3437 // when all AddrModes are trivial as then we would introduce a phi or select
3438 // which just duplicates what's already there.
3439 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3440
3441 // If this is the first addrmode then everything is fine.
3442 if (AddrModes.empty()) {
3443 AddrModes.emplace_back(NewAddrMode);
3444 return true;
3445 }
3446
3447 // Figure out how different this is from the other address modes, which we
3448 // can do just by comparing against the first one given that we only care
3449 // about the cumulative difference.
3450 ExtAddrMode::FieldName ThisDifferentField =
3451 AddrModes[0].compare(NewAddrMode);
3452 if (DifferentField == ExtAddrMode::NoField)
3453 DifferentField = ThisDifferentField;
3454 else if (DifferentField != ThisDifferentField)
3455 DifferentField = ExtAddrMode::MultipleFields;
3456
3457 // If this AddrMode is the same as all the others then everything is fine
3458 // (which should only happen when there is actually only one AddrMode).
3459 if (DifferentField == ExtAddrMode::NoField) {
3460 assert(AddrModes.size() == 1);
3461 return true;
3462 }
3463
3464 // If NewAddrMode differs in only one dimension then we can handle it by
3465 // inserting a phi/select later on.
3466 if (DifferentField != ExtAddrMode::MultipleFields) {
3467 AddrModes.emplace_back(NewAddrMode);
3468 return true;
3469 }
3470
3471 // We couldn't combine NewAddrMode with the rest, so return failure.
3472 AddrModes.clear();
3473 return false;
3474 }
3475
3476 /// \brief Combine the addressing modes we've collected into a single
3477 /// addressing mode.
3478 /// \return True iff we successfully combined them or we only had one so
3479 /// didn't need to combine them anyway.
3480 bool combineAddrModes() {
3481 // If we have no AddrModes then they can't be combined.
3482 if (AddrModes.size() == 0)
3483 return false;
3484
3485 // A single AddrMode can trivially be combined.
3486 if (AddrModes.size() == 1)
3487 return true;
3488
3489 // If the AddrModes we collected are all just equal to the value they are
3490 // derived from then combining them wouldn't do anything useful.
3491 if (AllAddrModesTrivial)
3492 return false;
3493
3494 // TODO: Combine multiple AddrModes by inserting a select or phi for the
3495 // field in which the AddrModes differ.
3496 return false;
3497 }
3498};
3499
Eugene Zelenko900b6332017-08-29 22:32:07 +00003500} // end anonymous namespace
3501
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003502/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003503/// Return true and update AddrMode if this addr mode is legal for the target,
3504/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003505bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003506 unsigned Depth) {
3507 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3508 // mode. Just process that directly.
3509 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003510 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003511
Chandler Carruthc8925912013-01-05 02:09:22 +00003512 // If the scale is 0, it takes nothing to add this.
3513 if (Scale == 0)
3514 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003515
Chandler Carruthc8925912013-01-05 02:09:22 +00003516 // If we already have a scale of this value, we can add to it, otherwise, we
3517 // need an available scale field.
3518 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3519 return false;
3520
3521 ExtAddrMode TestAddrMode = AddrMode;
3522
3523 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3524 // [A+B + A*7] -> [B+A*8].
3525 TestAddrMode.Scale += Scale;
3526 TestAddrMode.ScaledReg = ScaleReg;
3527
3528 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003529 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003530 return false;
3531
3532 // It was legal, so commit it.
3533 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003534
Chandler Carruthc8925912013-01-05 02:09:22 +00003535 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3536 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3537 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003538 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003539 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3540 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3541 TestAddrMode.ScaledReg = AddLHS;
3542 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003543
Chandler Carruthc8925912013-01-05 02:09:22 +00003544 // If this addressing mode is legal, commit it and remember that we folded
3545 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003546 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003547 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3548 AddrMode = TestAddrMode;
3549 return true;
3550 }
3551 }
3552
3553 // Otherwise, not (x+c)*scale, just return what we have.
3554 return true;
3555}
3556
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003557/// This is a little filter, which returns true if an addressing computation
3558/// involving I might be folded into a load/store accessing it.
3559/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003560/// the set of instructions that MatchOperationAddr can.
3561static bool MightBeFoldableInst(Instruction *I) {
3562 switch (I->getOpcode()) {
3563 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003564 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003565 // Don't touch identity bitcasts.
3566 if (I->getType() == I->getOperand(0)->getType())
3567 return false;
3568 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3569 case Instruction::PtrToInt:
3570 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3571 return true;
3572 case Instruction::IntToPtr:
3573 // We know the input is intptr_t, so this is foldable.
3574 return true;
3575 case Instruction::Add:
3576 return true;
3577 case Instruction::Mul:
3578 case Instruction::Shl:
3579 // Can only handle X*C and X << C.
3580 return isa<ConstantInt>(I->getOperand(1));
3581 case Instruction::GetElementPtr:
3582 return true;
3583 default:
3584 return false;
3585 }
3586}
3587
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003588/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3589/// \note \p Val is assumed to be the product of some type promotion.
3590/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3591/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003592static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3593 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003594 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3595 if (!PromotedInst)
3596 return false;
3597 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3598 // If the ISDOpcode is undefined, it was undefined before the promotion.
3599 if (!ISDOpcode)
3600 return true;
3601 // Otherwise, check if the promoted instruction is legal or not.
3602 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003603 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003604}
3605
Eugene Zelenko900b6332017-08-29 22:32:07 +00003606namespace {
3607
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003608/// \brief Hepler class to perform type promotion.
3609class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003610 /// \brief Utility function to check whether or not a sign or zero extension
3611 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3612 /// either using the operands of \p Inst or promoting \p Inst.
3613 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003614 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003615 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003616 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003617 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003618 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003619 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003620 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003621 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3622 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003623
3624 /// \brief Utility function to determine if \p OpIdx should be promoted when
3625 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003626 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003627 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003628 }
3629
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003630 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003631 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003632 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003633 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003634 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003635 /// Newly added extensions are inserted in \p Exts.
3636 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003637 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003638 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003639 static Value *promoteOperandForTruncAndAnyExt(
3640 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003641 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003642 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003643 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003644
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003645 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003646 /// operand is promotable and is not a supported trunc or sext.
3647 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003648 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003649 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003650 /// Newly added extensions are inserted in \p Exts.
3651 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003652 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003653 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003654 static Value *promoteOperandForOther(Instruction *Ext,
3655 TypePromotionTransaction &TPT,
3656 InstrToOrigTy &PromotedInsts,
3657 unsigned &CreatedInstsCost,
3658 SmallVectorImpl<Instruction *> *Exts,
3659 SmallVectorImpl<Instruction *> *Truncs,
3660 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003661
3662 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003663 static Value *signExtendOperandForOther(
3664 Instruction *Ext, TypePromotionTransaction &TPT,
3665 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3666 SmallVectorImpl<Instruction *> *Exts,
3667 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3668 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3669 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003670 }
3671
3672 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003673 static Value *zeroExtendOperandForOther(
3674 Instruction *Ext, TypePromotionTransaction &TPT,
3675 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3676 SmallVectorImpl<Instruction *> *Exts,
3677 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3678 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3679 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003680 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003681
3682public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003683 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003684 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3685 InstrToOrigTy &PromotedInsts,
3686 unsigned &CreatedInstsCost,
3687 SmallVectorImpl<Instruction *> *Exts,
3688 SmallVectorImpl<Instruction *> *Truncs,
3689 const TargetLowering &TLI);
3690
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003691 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3692 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003693 /// \return NULL if no promotable action is possible with the current
3694 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003695 /// \p InsertedInsts keeps track of all the instructions inserted by the
3696 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003697 /// because we do not want to promote these instructions as CodeGenPrepare
3698 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3699 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003700 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003701 const TargetLowering &TLI,
3702 const InstrToOrigTy &PromotedInsts);
3703};
3704
Eugene Zelenko900b6332017-08-29 22:32:07 +00003705} // end anonymous namespace
3706
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003707bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003708 Type *ConsideredExtType,
3709 const InstrToOrigTy &PromotedInsts,
3710 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003711 // The promotion helper does not know how to deal with vector types yet.
3712 // To be able to fix that, we would need to fix the places where we
3713 // statically extend, e.g., constants and such.
3714 if (Inst->getType()->isVectorTy())
3715 return false;
3716
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003717 // We can always get through zext.
3718 if (isa<ZExtInst>(Inst))
3719 return true;
3720
3721 // sext(sext) is ok too.
3722 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003723 return true;
3724
3725 // We can get through binary operator, if it is legal. In other words, the
3726 // binary operator must have a nuw or nsw flag.
3727 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3728 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003729 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3730 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003731 return true;
3732
3733 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003734 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003735 if (!isa<TruncInst>(Inst))
3736 return false;
3737
3738 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003739 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003740 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003741 if (!OpndVal->getType()->isIntegerTy() ||
3742 OpndVal->getType()->getIntegerBitWidth() >
3743 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003744 return false;
3745
3746 // If the operand of the truncate is not an instruction, we will not have
3747 // any information on the dropped bits.
3748 // (Actually we could for constant but it is not worth the extra logic).
3749 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3750 if (!Opnd)
3751 return false;
3752
3753 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003754 // I.e., check that trunc just drops extended bits of the same kind of
3755 // the extension.
3756 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003757 const Type *OpndType;
3758 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003759 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3760 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003761 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3762 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003763 else
3764 return false;
3765
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003766 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003767 return Inst->getType()->getIntegerBitWidth() >=
3768 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003769}
3770
3771TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003772 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003773 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003774 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3775 "Unexpected instruction type");
3776 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3777 Type *ExtTy = Ext->getType();
3778 bool IsSExt = isa<SExtInst>(Ext);
3779 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003780 // get through.
3781 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003782 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003783 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003784
3785 // Do not promote if the operand has been added by codegenprepare.
3786 // Otherwise, it means we are undoing an optimization that is likely to be
3787 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003788 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003789 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003790
3791 // SExt or Trunc instructions.
3792 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003793 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3794 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003795 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003796
3797 // Regular instruction.
3798 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003799 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003800 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003801 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003802}
3803
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003804Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003805 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003806 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003807 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003808 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003809 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3810 // get through it and this method should not be called.
3811 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003812 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003813 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003814 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003815 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003816 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003817 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003818 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003819 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3820 TPT.replaceAllUsesWith(SExt, ZExt);
3821 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003822 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003823 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003824 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3825 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003826 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3827 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003828 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003829
3830 // Remove dead code.
3831 if (SExtOpnd->use_empty())
3832 TPT.eraseInstruction(SExtOpnd);
3833
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003834 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003835 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003836 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003837 if (ExtInst) {
3838 if (Exts)
3839 Exts->push_back(ExtInst);
3840 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3841 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003842 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003843 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003844
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003845 // At this point we have: ext ty opnd to ty.
3846 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3847 Value *NextVal = ExtInst->getOperand(0);
3848 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003849 return NextVal;
3850}
3851
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003852Value *TypePromotionHelper::promoteOperandForOther(
3853 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003854 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003855 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003856 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3857 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003858 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003859 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003860 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003861 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003862 if (!ExtOpnd->hasOneUse()) {
3863 // ExtOpnd will be promoted.
3864 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003865 // promoted version.
3866 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003867 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003868 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003869 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003870 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003871 if (Truncs)
3872 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003873 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003874
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003875 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003876 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003877 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003878 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003879 }
3880
3881 // Get through the Instruction:
3882 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003883 // 2. Replace the uses of Ext by Inst.
3884 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003885
3886 // Remember the original type of the instruction before promotion.
3887 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003888 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3889 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003890 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003891 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003892 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003893 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003894 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003895 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003896
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003897 DEBUG(dbgs() << "Propagate Ext to operands\n");
3898 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003899 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003900 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3901 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3902 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003903 DEBUG(dbgs() << "No need to propagate\n");
3904 continue;
3905 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003906 // Check if we can statically extend the operand.
3907 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003908 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003909 DEBUG(dbgs() << "Statically extend\n");
3910 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3911 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3912 : Cst->getValue().zext(BitWidth);
3913 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003914 continue;
3915 }
3916 // UndefValue are typed, so we have to statically sign extend them.
3917 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003918 DEBUG(dbgs() << "Statically extend\n");
3919 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003920 continue;
3921 }
3922
3923 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003924 // Check if Ext was reused to extend an operand.
3925 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003926 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003927 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003928 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3929 : TPT.createZExt(Ext, Opnd, Ext->getType());
3930 if (!isa<Instruction>(ValForExtOpnd)) {
3931 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3932 continue;
3933 }
3934 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003935 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003936 if (Exts)
3937 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003938 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003939
3940 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003941 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3942 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003943 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003944 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003945 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003946 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003947 if (ExtForOpnd == Ext) {
3948 DEBUG(dbgs() << "Extension is useless now\n");
3949 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003950 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003951 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003952}
3953
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003954/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003955/// \p NewCost gives the cost of extension instructions created by the
3956/// promotion.
3957/// \p OldCost gives the cost of extension instructions before the promotion
3958/// plus the number of instructions that have been
3959/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003960/// \p PromotedOperand is the value that has been promoted.
3961/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003962bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003963 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3964 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3965 // The cost of the new extensions is greater than the cost of the
3966 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003967 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003968 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003969 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003970 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003971 return true;
3972 // The promotion is neutral but it may help folding the sign extension in
3973 // loads for instance.
3974 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003975 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003976}
3977
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003978/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003979/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003980/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003981/// If \p MovedAway is not NULL, it contains the information of whether or
3982/// not AddrInst has to be folded into the addressing mode on success.
3983/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3984/// because it has been moved away.
3985/// Thus AddrInst must not be added in the matched instructions.
3986/// This state can happen when AddrInst is a sext, since it may be moved away.
3987/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3988/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003989bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003990 unsigned Depth,
3991 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003992 // Avoid exponential behavior on extremely deep expression trees.
3993 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003994
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003995 // By default, all matched instructions stay in place.
3996 if (MovedAway)
3997 *MovedAway = false;
3998
Chandler Carruthc8925912013-01-05 02:09:22 +00003999 switch (Opcode) {
4000 case Instruction::PtrToInt:
4001 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004002 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00004003 case Instruction::IntToPtr: {
4004 auto AS = AddrInst->getType()->getPointerAddressSpace();
4005 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00004006 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00004007 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00004008 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004009 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00004010 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004011 case Instruction::BitCast:
4012 // BitCast is always a noop, and we can handle it as long as it is
4013 // int->int or pointer->pointer (we don't want int<->fp or something).
4014 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
4015 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
4016 // Don't touch identity bitcasts. These were probably put here by LSR,
4017 // and we don't want to mess around with them. Assume it knows what it
4018 // is doing.
4019 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00004020 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004021 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00004022 case Instruction::AddrSpaceCast: {
4023 unsigned SrcAS
4024 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4025 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4026 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004027 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00004028 return false;
4029 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004030 case Instruction::Add: {
4031 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4032 ExtAddrMode BackupAddrMode = AddrMode;
4033 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004034 // Start a transaction at this point.
4035 // The LHS may match but not the RHS.
4036 // Therefore, we need a higher level restoration point to undo partially
4037 // matched operation.
4038 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4039 TPT.getRestorationPoint();
4040
Sanjay Patelfc580a62015-09-21 23:03:16 +00004041 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
4042 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004043 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004044
Chandler Carruthc8925912013-01-05 02:09:22 +00004045 // Restore the old addr mode info.
4046 AddrMode = BackupAddrMode;
4047 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004048 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00004049
Chandler Carruthc8925912013-01-05 02:09:22 +00004050 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004051 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4052 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004053 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004054
Chandler Carruthc8925912013-01-05 02:09:22 +00004055 // Otherwise we definitely can't merge the ADD in.
4056 AddrMode = BackupAddrMode;
4057 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004058 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004059 break;
4060 }
4061 //case Instruction::Or:
4062 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4063 //break;
4064 case Instruction::Mul:
4065 case Instruction::Shl: {
4066 // Can only handle X*C and X << C.
4067 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004068 if (!RHS)
4069 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00004070 int64_t Scale = RHS->getSExtValue();
4071 if (Opcode == Instruction::Shl)
4072 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00004073
Sanjay Patelfc580a62015-09-21 23:03:16 +00004074 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00004075 }
4076 case Instruction::GetElementPtr: {
4077 // Scan the GEP. We check it if it contains constant offsets and at most
4078 // one variable offset.
4079 int VariableOperand = -1;
4080 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00004081
Chandler Carruthc8925912013-01-05 02:09:22 +00004082 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00004083 gep_type_iterator GTI = gep_type_begin(AddrInst);
4084 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00004085 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00004086 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00004087 unsigned Idx =
4088 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4089 ConstantOffset += SL->getElementOffset(Idx);
4090 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00004091 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00004092 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4093 ConstantOffset += CI->getSExtValue()*TypeSize;
4094 } else if (TypeSize) { // Scales of zero don't do anything.
4095 // We only allow one variable index at the moment.
4096 if (VariableOperand != -1)
4097 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004098
Chandler Carruthc8925912013-01-05 02:09:22 +00004099 // Remember the variable index.
4100 VariableOperand = i;
4101 VariableScale = TypeSize;
4102 }
4103 }
4104 }
Stephen Lin837bba12013-07-15 17:55:02 +00004105
Chandler Carruthc8925912013-01-05 02:09:22 +00004106 // A common case is for the GEP to only do a constant offset. In this case,
4107 // just add it to the disp field and check validity.
4108 if (VariableOperand == -1) {
4109 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004110 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004111 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004112 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004113 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004114 return true;
4115 }
4116 AddrMode.BaseOffs -= ConstantOffset;
4117 return false;
4118 }
4119
4120 // Save the valid addressing mode in case we can't match.
4121 ExtAddrMode BackupAddrMode = AddrMode;
4122 unsigned OldSize = AddrModeInsts.size();
4123
4124 // See if the scale and offset amount is valid for this target.
4125 AddrMode.BaseOffs += ConstantOffset;
4126
4127 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004128 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004129 // If it couldn't be matched, just stuff the value in a register.
4130 if (AddrMode.HasBaseReg) {
4131 AddrMode = BackupAddrMode;
4132 AddrModeInsts.resize(OldSize);
4133 return false;
4134 }
4135 AddrMode.HasBaseReg = true;
4136 AddrMode.BaseReg = AddrInst->getOperand(0);
4137 }
4138
4139 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004140 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00004141 Depth)) {
4142 // If it couldn't be matched, try stuffing the base into a register
4143 // instead of matching it, and retrying the match of the scale.
4144 AddrMode = BackupAddrMode;
4145 AddrModeInsts.resize(OldSize);
4146 if (AddrMode.HasBaseReg)
4147 return false;
4148 AddrMode.HasBaseReg = true;
4149 AddrMode.BaseReg = AddrInst->getOperand(0);
4150 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004151 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00004152 VariableScale, Depth)) {
4153 // If even that didn't work, bail.
4154 AddrMode = BackupAddrMode;
4155 AddrModeInsts.resize(OldSize);
4156 return false;
4157 }
4158 }
4159
4160 return true;
4161 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004162 case Instruction::SExt:
4163 case Instruction::ZExt: {
4164 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4165 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004166 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00004167
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004168 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004169 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004170 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004171 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004172 if (!TPH)
4173 return false;
4174
4175 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4176 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00004177 unsigned CreatedInstsCost = 0;
4178 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004179 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00004180 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004181 // SExt has been moved away.
4182 // Thus either it will be rematched later in the recursive calls or it is
4183 // gone. Anyway, we must not fold it into the addressing mode at this point.
4184 // E.g.,
4185 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004186 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004187 // addr = gep base, idx
4188 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004189 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004190 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4191 // addr = gep base, op <- match
4192 if (MovedAway)
4193 *MovedAway = true;
4194
4195 assert(PromotedOperand &&
4196 "TypePromotionHelper should have filtered out those cases");
4197
4198 ExtAddrMode BackupAddrMode = AddrMode;
4199 unsigned OldSize = AddrModeInsts.size();
4200
Sanjay Patelfc580a62015-09-21 23:03:16 +00004201 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004202 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00004203 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004204 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00004205 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004206 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004207 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00004208 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004209 AddrMode = BackupAddrMode;
4210 AddrModeInsts.resize(OldSize);
4211 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
4212 TPT.rollback(LastKnownGood);
4213 return false;
4214 }
4215 return true;
4216 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004217 }
4218 return false;
4219}
4220
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004221/// If we can, try to add the value of 'Addr' into the current addressing mode.
4222/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4223/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4224/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00004225///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004226bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004227 // Start a transaction at this point that we will rollback if the matching
4228 // fails.
4229 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4230 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00004231 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4232 // Fold in immediates if legal for the target.
4233 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004234 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004235 return true;
4236 AddrMode.BaseOffs -= CI->getSExtValue();
4237 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4238 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004239 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004240 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004241 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004242 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004243 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004244 }
4245 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4246 ExtAddrMode BackupAddrMode = AddrMode;
4247 unsigned OldSize = AddrModeInsts.size();
4248
4249 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004250 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004251 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004252 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004253 // to check here.
4254 if (MovedAway)
4255 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004256 // Okay, it's possible to fold this. Check to see if it is actually
4257 // *profitable* to do so. We use a simple cost model to avoid increasing
4258 // register pressure too much.
4259 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004260 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004261 AddrModeInsts.push_back(I);
4262 return true;
4263 }
Stephen Lin837bba12013-07-15 17:55:02 +00004264
Chandler Carruthc8925912013-01-05 02:09:22 +00004265 // It isn't profitable to do this, roll back.
4266 //cerr << "NOT FOLDING: " << *I;
4267 AddrMode = BackupAddrMode;
4268 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004269 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004270 }
4271 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004272 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004273 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004274 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004275 } else if (isa<ConstantPointerNull>(Addr)) {
4276 // Null pointer gets folded without affecting the addressing mode.
4277 return true;
4278 }
4279
4280 // Worse case, the target should support [reg] addressing modes. :)
4281 if (!AddrMode.HasBaseReg) {
4282 AddrMode.HasBaseReg = true;
4283 AddrMode.BaseReg = Addr;
4284 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004285 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004286 return true;
4287 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004288 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004289 }
4290
4291 // If the base register is already taken, see if we can do [r+r].
4292 if (AddrMode.Scale == 0) {
4293 AddrMode.Scale = 1;
4294 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004295 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004296 return true;
4297 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004298 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004299 }
4300 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004301 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004302 return false;
4303}
4304
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004305/// Check to see if all uses of OpVal by the specified inline asm call are due
4306/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004307static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004308 const TargetLowering &TLI,
4309 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004310 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004311 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004312 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004313 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004314
Chandler Carruthc8925912013-01-05 02:09:22 +00004315 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4316 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004317
Chandler Carruthc8925912013-01-05 02:09:22 +00004318 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004319 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004320
4321 // If this asm operand is our Value*, and if it isn't an indirect memory
4322 // operand, we can't fold it!
4323 if (OpInfo.CallOperandVal == OpVal &&
4324 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4325 !OpInfo.isIndirect))
4326 return false;
4327 }
4328
4329 return true;
4330}
4331
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004332// Max number of memory uses to look at before aborting the search to conserve
4333// compile time.
4334static constexpr int MaxMemoryUsesToScan = 20;
4335
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004336/// Recursively walk all the uses of I until we find a memory use.
4337/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004338/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004339static bool FindAllMemoryUses(
4340 Instruction *I,
4341 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004342 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4343 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004344 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004345 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004346 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004347
Chandler Carruthc8925912013-01-05 02:09:22 +00004348 // If this is an obviously unfoldable instruction, bail out.
4349 if (!MightBeFoldableInst(I))
4350 return true;
4351
Philip Reamesac115ed2016-03-09 23:13:12 +00004352 const bool OptSize = I->getFunction()->optForSize();
4353
Chandler Carruthc8925912013-01-05 02:09:22 +00004354 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004355 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004356 // Conservatively return true if we're seeing a large number or a deep chain
4357 // of users. This avoids excessive compilation times in pathological cases.
4358 if (SeenInsts++ >= MaxMemoryUsesToScan)
4359 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004360
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004361 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004362 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4363 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004364 continue;
4365 }
Stephen Lin837bba12013-07-15 17:55:02 +00004366
Chandler Carruthcdf47882014-03-09 03:16:01 +00004367 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4368 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004369 if (opNo != StoreInst::getPointerOperandIndex())
4370 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004371 MemoryUses.push_back(std::make_pair(SI, opNo));
4372 continue;
4373 }
Stephen Lin837bba12013-07-15 17:55:02 +00004374
Matt Arsenault02d915b2017-03-15 22:35:20 +00004375 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4376 unsigned opNo = U.getOperandNo();
4377 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4378 return true; // Storing addr, not into addr.
4379 MemoryUses.push_back(std::make_pair(RMW, opNo));
4380 continue;
4381 }
4382
4383 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4384 unsigned opNo = U.getOperandNo();
4385 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4386 return true; // Storing addr, not into addr.
4387 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4388 continue;
4389 }
4390
Chandler Carruthcdf47882014-03-09 03:16:01 +00004391 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004392 // If this is a cold call, we can sink the addressing calculation into
4393 // the cold path. See optimizeCallInst
4394 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4395 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004396
Chandler Carruthc8925912013-01-05 02:09:22 +00004397 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4398 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004399
Chandler Carruthc8925912013-01-05 02:09:22 +00004400 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004401 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004402 return true;
4403 continue;
4404 }
Stephen Lin837bba12013-07-15 17:55:02 +00004405
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004406 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4407 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004408 return true;
4409 }
4410
4411 return false;
4412}
4413
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004414/// Return true if Val is already known to be live at the use site that we're
4415/// folding it into. If so, there is no cost to include it in the addressing
4416/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4417/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004418bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004419 Value *KnownLive2) {
4420 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004421 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004422 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004423
Chandler Carruthc8925912013-01-05 02:09:22 +00004424 // All values other than instructions and arguments (e.g. constants) are live.
4425 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004426
Chandler Carruthc8925912013-01-05 02:09:22 +00004427 // If Val is a constant sized alloca in the entry block, it is live, this is
4428 // true because it is just a reference to the stack/frame pointer, which is
4429 // live for the whole function.
4430 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4431 if (AI->isStaticAlloca())
4432 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004433
Chandler Carruthc8925912013-01-05 02:09:22 +00004434 // Check to see if this value is already used in the memory instruction's
4435 // block. If so, it's already live into the block at the very least, so we
4436 // can reasonably fold it.
4437 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4438}
4439
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004440/// It is possible for the addressing mode of the machine to fold the specified
4441/// instruction into a load or store that ultimately uses it.
4442/// However, the specified instruction has multiple uses.
4443/// Given this, it may actually increase register pressure to fold it
4444/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004445///
4446/// X = ...
4447/// Y = X+1
4448/// use(Y) -> nonload/store
4449/// Z = Y+1
4450/// load Z
4451///
4452/// In this case, Y has multiple uses, and can be folded into the load of Z
4453/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4454/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4455/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4456/// number of computations either.
4457///
4458/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4459/// X was live across 'load Z' for other reasons, we actually *would* want to
4460/// fold the addressing mode in the Z case. This would make Y die earlier.
4461bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004462isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004463 ExtAddrMode &AMAfter) {
4464 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004465
Chandler Carruthc8925912013-01-05 02:09:22 +00004466 // AMBefore is the addressing mode before this instruction was folded into it,
4467 // and AMAfter is the addressing mode after the instruction was folded. Get
4468 // the set of registers referenced by AMAfter and subtract out those
4469 // referenced by AMBefore: this is the set of values which folding in this
4470 // address extends the lifetime of.
4471 //
4472 // Note that there are only two potential values being referenced here,
4473 // BaseReg and ScaleReg (global addresses are always available, as are any
4474 // folded immediates).
4475 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004476
Chandler Carruthc8925912013-01-05 02:09:22 +00004477 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4478 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004479 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004480 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004481 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004482 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004483
4484 // If folding this instruction (and it's subexprs) didn't extend any live
4485 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004486 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004487 return true;
4488
Philip Reamesac115ed2016-03-09 23:13:12 +00004489 // If all uses of this instruction can have the address mode sunk into them,
4490 // we can remove the addressing mode and effectively trade one live register
4491 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004492 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004493 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4494 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004495 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004496 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004497
Chandler Carruthc8925912013-01-05 02:09:22 +00004498 // Now that we know that all uses of this instruction are part of a chain of
4499 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004500 // into a memory use, loop over each of these memory operation uses and see
4501 // if they could *actually* fold the instruction. The assumption is that
4502 // addressing modes are cheap and that duplicating the computation involved
4503 // many times is worthwhile, even on a fastpath. For sinking candidates
4504 // (i.e. cold call sites), this serves as a way to prevent excessive code
4505 // growth since most architectures have some reasonable small and fast way to
4506 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004507 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4508 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4509 Instruction *User = MemoryUses[i].first;
4510 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004511
Chandler Carruthc8925912013-01-05 02:09:22 +00004512 // Get the access type of this use. If the use isn't a pointer, we don't
4513 // know what it accesses.
4514 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004515 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4516 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004517 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004518 Type *AddressAccessTy = AddrTy->getElementType();
4519 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004520
Chandler Carruthc8925912013-01-05 02:09:22 +00004521 // Do a match against the root of this address, ignoring profitability. This
4522 // will tell us if the addressing mode for the memory operation will
4523 // *actually* cover the shared instruction.
4524 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004525 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4526 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004527 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4528 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004529 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004530 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004531 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004532 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004533 (void)Success; assert(Success && "Couldn't select *anything*?");
4534
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004535 // The match was to check the profitability, the changes made are not
4536 // part of the original matcher. Therefore, they should be dropped
4537 // otherwise the original matcher will not present the right state.
4538 TPT.rollback(LastKnownGood);
4539
Chandler Carruthc8925912013-01-05 02:09:22 +00004540 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004541 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004542 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004543
Chandler Carruthc8925912013-01-05 02:09:22 +00004544 MatchedAddrModeInsts.clear();
4545 }
Stephen Lin837bba12013-07-15 17:55:02 +00004546
Chandler Carruthc8925912013-01-05 02:09:22 +00004547 return true;
4548}
4549
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004550/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004551/// different basic block than BB.
4552static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4553 if (Instruction *I = dyn_cast<Instruction>(V))
4554 return I->getParent() != BB;
4555 return false;
4556}
4557
Philip Reamesac115ed2016-03-09 23:13:12 +00004558/// Sink addressing mode computation immediate before MemoryInst if doing so
4559/// can be done without increasing register pressure. The need for the
4560/// register pressure constraint means this can end up being an all or nothing
4561/// decision for all uses of the same addressing computation.
4562///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004563/// Load and Store Instructions often have addressing modes that can do
4564/// significant amounts of computation. As such, instruction selection will try
4565/// to get the load or store to do as much computation as possible for the
4566/// program. The problem is that isel can only see within a single block. As
4567/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004568///
4569/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004570/// operands. It's also used to sink addressing computations feeding into cold
4571/// call sites into their (cold) basic block.
4572///
4573/// The motivation for handling sinking into cold blocks is that doing so can
4574/// both enable other address mode sinking (by satisfying the register pressure
4575/// constraint above), and reduce register pressure globally (by removing the
4576/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004577bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004578 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004579 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004580
4581 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004582 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004583 SmallVector<Value*, 8> worklist;
4584 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004585 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004586
John Brawneb83c752017-10-03 13:04:15 +00004587 // Use a worklist to iteratively look through PHI and select nodes, and
4588 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004589 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004590 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004591 SmallVector<Instruction*, 16> AddrModeInsts;
John Brawn736bf002017-10-03 13:08:22 +00004592 AddressingModeCombiner AddrModes;
Jun Bum Limdee55652017-04-03 19:20:07 +00004593 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004594 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4595 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004596 while (!worklist.empty()) {
4597 Value *V = worklist.back();
4598 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004599
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004600 // We allow traversing cyclic Phi nodes.
4601 // In case of success after this loop we ensure that traversing through
4602 // Phi nodes ends up with all cases to compute address of the form
4603 // BaseGV + Base + Scale * Index + Offset
4604 // where Scale and Offset are constans and BaseGV, Base and Index
4605 // are exactly the same Values in all cases.
4606 // It means that BaseGV, Scale and Offset dominate our memory instruction
4607 // and have the same value as they had in address computation represented
4608 // as Phi. So we can safely sink address computation to memory instruction.
4609 if (!Visited.insert(V).second)
4610 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004611
Owen Anderson8ba5f392010-11-27 08:15:55 +00004612 // For a PHI node, push all of its incoming values.
4613 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004614 for (Value *IncValue : P->incoming_values())
4615 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004616 PhiOrSelectSeen = true;
4617 continue;
4618 }
4619 // Similar for select.
4620 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4621 worklist.push_back(SI->getFalseValue());
4622 worklist.push_back(SI->getTrueValue());
4623 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004624 continue;
4625 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004626
Philip Reamesac115ed2016-03-09 23:13:12 +00004627 // For non-PHIs, determine the addressing mode being computed. Note that
4628 // the result may differ depending on what other uses our candidate
4629 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004630 AddrModeInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004631 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004632 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4633 InsertedInsts, PromotedInsts, TPT);
John Brawn736bf002017-10-03 13:08:22 +00004634 NewAddrMode.OriginalValue = V;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004635
John Brawn736bf002017-10-03 13:08:22 +00004636 if (!AddrModes.addNewAddrMode(NewAddrMode))
4637 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004638 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004639
John Brawn736bf002017-10-03 13:08:22 +00004640 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4641 // or we have multiple but either couldn't combine them or combining them
4642 // wouldn't do anything useful, bail out now.
4643 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004644 TPT.rollback(LastKnownGood);
4645 return false;
4646 }
4647 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004648
John Brawn736bf002017-10-03 13:08:22 +00004649 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4650 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4651
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004652 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004653 // If we saw a Phi node then it is not local definitely, and if we saw a select
4654 // then we want to push the address calculation past it even if it's already
4655 // in this BB.
4656 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004657 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004658 })) {
David Greene74e2d492010-01-05 01:27:11 +00004659 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004660 return false;
4661 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004662
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004663 // Insert this computation right after this user. Since our caller is
4664 // scanning from the top of the BB to the bottom, reuse of the expr are
4665 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004666 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004667
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004668 // Now that we determined the addressing expression we want to use and know
4669 // that we have to sink it into this block. Check to see if we have already
4670 // done this for some other load/store instr in this block. If so, reuse the
4671 // computation.
4672 Value *&SunkAddr = SunkAddrs[Addr];
4673 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004674 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004675 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004676 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004677 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004678 } else if (AddrSinkUsingGEPs ||
4679 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004680 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004681 // By default, we use the GEP-based method when AA is used later. This
4682 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4683 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004684 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004685 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004686 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004687
4688 // First, find the pointer.
4689 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4690 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004691 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004692 }
4693
4694 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4695 // We can't add more than one pointer together, nor can we scale a
4696 // pointer (both of which seem meaningless).
4697 if (ResultPtr || AddrMode.Scale != 1)
4698 return false;
4699
4700 ResultPtr = AddrMode.ScaledReg;
4701 AddrMode.Scale = 0;
4702 }
4703
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004704 // It is only safe to sign extend the BaseReg if we know that the math
4705 // required to create it did not overflow before we extend it. Since
4706 // the original IR value was tossed in favor of a constant back when
4707 // the AddrMode was created we need to bail out gracefully if widths
4708 // do not match instead of extending it.
4709 //
4710 // (See below for code to add the scale.)
4711 if (AddrMode.Scale) {
4712 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4713 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4714 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4715 return false;
4716 }
4717
Hal Finkelc3998302014-04-12 00:59:48 +00004718 if (AddrMode.BaseGV) {
4719 if (ResultPtr)
4720 return false;
4721
4722 ResultPtr = AddrMode.BaseGV;
4723 }
4724
4725 // If the real base value actually came from an inttoptr, then the matcher
4726 // will look through it and provide only the integer value. In that case,
4727 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004728 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4729 if (!ResultPtr && AddrMode.BaseReg) {
4730 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4731 "sunkaddr");
4732 AddrMode.BaseReg = nullptr;
4733 } else if (!ResultPtr && AddrMode.Scale == 1) {
4734 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4735 "sunkaddr");
4736 AddrMode.Scale = 0;
4737 }
Hal Finkelc3998302014-04-12 00:59:48 +00004738 }
4739
4740 if (!ResultPtr &&
4741 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4742 SunkAddr = Constant::getNullValue(Addr->getType());
4743 } else if (!ResultPtr) {
4744 return false;
4745 } else {
4746 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004747 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4748 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004749
4750 // Start with the base register. Do this first so that subsequent address
4751 // matching finds it last, which will prevent it from trying to match it
4752 // as the scaled value in case it happens to be a mul. That would be
4753 // problematic if we've sunk a different mul for the scale, because then
4754 // we'd end up sinking both muls.
4755 if (AddrMode.BaseReg) {
4756 Value *V = AddrMode.BaseReg;
4757 if (V->getType() != IntPtrTy)
4758 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4759
4760 ResultIndex = V;
4761 }
4762
4763 // Add the scale value.
4764 if (AddrMode.Scale) {
4765 Value *V = AddrMode.ScaledReg;
4766 if (V->getType() == IntPtrTy) {
4767 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004768 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004769 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4770 cast<IntegerType>(V->getType())->getBitWidth() &&
4771 "We can't transform if ScaledReg is too narrow");
4772 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004773 }
4774
4775 if (AddrMode.Scale != 1)
4776 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4777 "sunkaddr");
4778 if (ResultIndex)
4779 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4780 else
4781 ResultIndex = V;
4782 }
4783
4784 // Add in the Base Offset if present.
4785 if (AddrMode.BaseOffs) {
4786 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4787 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004788 // We need to add this separately from the scale above to help with
4789 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004790 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004791 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004792 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004793 }
4794
4795 ResultIndex = V;
4796 }
4797
4798 if (!ResultIndex) {
4799 SunkAddr = ResultPtr;
4800 } else {
4801 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004802 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004803 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004804 }
4805
4806 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004807 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004808 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004809 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004810 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4811 // non-integral pointers, so in that case bail out now.
4812 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4813 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4814 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4815 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4816 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4817 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4818 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4819 (AddrMode.BaseGV &&
4820 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4821 return false;
4822
David Greene74e2d492010-01-05 01:27:11 +00004823 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004824 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004825 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004826 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004827
4828 // Start with the base register. Do this first so that subsequent address
4829 // matching finds it last, which will prevent it from trying to match it
4830 // as the scaled value in case it happens to be a mul. That would be
4831 // problematic if we've sunk a different mul for the scale, because then
4832 // we'd end up sinking both muls.
4833 if (AddrMode.BaseReg) {
4834 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004835 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004836 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004837 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004838 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004839 Result = V;
4840 }
4841
4842 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004843 if (AddrMode.Scale) {
4844 Value *V = AddrMode.ScaledReg;
4845 if (V->getType() == IntPtrTy) {
4846 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004847 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004848 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004849 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4850 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004851 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004852 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004853 // It is only safe to sign extend the BaseReg if we know that the math
4854 // required to create it did not overflow before we extend it. Since
4855 // the original IR value was tossed in favor of a constant back when
4856 // the AddrMode was created we need to bail out gracefully if widths
4857 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004858 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004859 if (I && (Result != AddrMode.BaseReg))
4860 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004861 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004862 }
4863 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004864 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4865 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004866 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004867 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004868 else
4869 Result = V;
4870 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004871
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004872 // Add in the BaseGV if present.
4873 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004874 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004875 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004876 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004877 else
4878 Result = V;
4879 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004880
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004881 // Add in the Base Offset if present.
4882 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004883 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004884 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004885 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004886 else
4887 Result = V;
4888 }
4889
Craig Topperc0196b12014-04-14 00:51:57 +00004890 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004891 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004892 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004893 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004894 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004895
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004896 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004897
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004898 // If we have no uses, recursively delete the value and all dead instructions
4899 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004900 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004901 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004902 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004903 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004904 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004905 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004906
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004907 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004908
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004909 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004910 // If the iterator instruction was recursively deleted, start over at the
4911 // start of the block.
4912 CurInstIterator = BB->begin();
4913 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004914 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004915 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004916 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004917 return true;
4918}
4919
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004920/// If there are any memory operands, use OptimizeMemoryInst to sink their
4921/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004922bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004923 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004924
Eric Christopher11e4df72015-02-26 22:38:43 +00004925 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004926 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004927 TargetLowering::AsmOperandInfoVector TargetConstraints =
4928 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004929 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004930 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4931 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004932
Evan Cheng1da25002008-02-26 02:42:37 +00004933 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004934 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004935
Eli Friedman666bbe32008-02-26 18:37:49 +00004936 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4937 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004938 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004939 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004940 } else if (OpInfo.Type == InlineAsm::isInput)
4941 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004942 }
4943
4944 return MadeChange;
4945}
4946
Jun Bum Lim42301012017-03-17 19:05:21 +00004947/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004948/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004949static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4950 assert(!Val->use_empty() && "Input must have at least one use");
4951 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004952 bool IsSExt = isa<SExtInst>(FirstUser);
4953 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004954 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004955 const Instruction *UI = cast<Instruction>(U);
4956 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4957 return false;
4958 Type *CurTy = UI->getType();
4959 // Same input and output types: Same instruction after CSE.
4960 if (CurTy == ExtTy)
4961 continue;
4962
4963 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004964 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004965 // b = sext ty1 a to ty2
4966 // c = sext ty1 a to ty3
4967 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004968 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004969 // b = sext ty1 a to ty2
4970 // c = sext ty2 b to ty3
4971 // However, the last sext is not free.
4972 if (IsSExt)
4973 return false;
4974
4975 // This is a ZExt, maybe this is free to extend from one type to another.
4976 // In that case, we would not account for a different use.
4977 Type *NarrowTy;
4978 Type *LargeTy;
4979 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4980 CurTy->getScalarType()->getIntegerBitWidth()) {
4981 NarrowTy = CurTy;
4982 LargeTy = ExtTy;
4983 } else {
4984 NarrowTy = ExtTy;
4985 LargeTy = CurTy;
4986 }
4987
4988 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4989 return false;
4990 }
4991 // All uses are the same or can be derived from one another for free.
4992 return true;
4993}
4994
Jun Bum Lim42301012017-03-17 19:05:21 +00004995/// \brief Try to speculatively promote extensions in \p Exts and continue
4996/// promoting through newly promoted operands recursively as far as doing so is
4997/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4998/// When some promotion happened, \p TPT contains the proper state to revert
4999/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005000///
Jun Bum Lim42301012017-03-17 19:05:21 +00005001/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00005002bool CodeGenPrepare::tryToPromoteExts(
5003 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
5004 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
5005 unsigned CreatedInstsCost) {
5006 bool Promoted = false;
5007
5008 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005009 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00005010 // Early check if we directly have ext(load).
5011 if (isa<LoadInst>(I->getOperand(0))) {
5012 ProfitablyMovedExts.push_back(I);
5013 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005014 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005015
5016 // Check whether or not we want to do any promotion. The reason we have
5017 // this check inside the for loop is to catch the case where an extension
5018 // is directly fed by a load because in such case the extension can be moved
5019 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005020 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00005021 return false;
5022
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005023 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00005024 TypePromotionHelper::Action TPH =
5025 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005026 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00005027 if (!TPH) {
5028 // Save the current extension as we cannot move up through its operand.
5029 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005030 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00005031 }
5032
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005033 // Save the current state.
5034 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5035 TPT.getRestorationPoint();
5036 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00005037 unsigned NewCreatedInstsCost = 0;
5038 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005039 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00005040 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5041 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005042 assert(PromotedVal &&
5043 "TypePromotionHelper should have filtered out those cases");
5044
5045 // We would be able to merge only one extension in a load.
5046 // Therefore, if we have more than 1 new extension we heuristically
5047 // cut this search path, because it means we degrade the code quality.
5048 // With exactly 2, the transformation is neutral, because we will merge
5049 // one extension but leave one. However, we optimistically keep going,
5050 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00005051 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005052 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00005053 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005054 TotalCreatedInstsCost =
5055 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005056 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00005057 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00005058 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00005059 // This promotion is not profitable, rollback to the previous state, and
5060 // save the current extension in ProfitablyMovedExts as the latest
5061 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005062 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00005063 ProfitablyMovedExts.push_back(I);
5064 continue;
5065 }
5066 // Continue promoting NewExts as far as doing so is profitable.
5067 SmallVector<Instruction *, 2> NewlyMovedExts;
5068 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5069 bool NewPromoted = false;
5070 for (auto ExtInst : NewlyMovedExts) {
5071 Instruction *MovedExt = cast<Instruction>(ExtInst);
5072 Value *ExtOperand = MovedExt->getOperand(0);
5073 // If we have reached to a load, we need this extra profitability check
5074 // as it could potentially be merged into an ext(load).
5075 if (isa<LoadInst>(ExtOperand) &&
5076 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5077 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5078 continue;
5079
5080 ProfitablyMovedExts.push_back(MovedExt);
5081 NewPromoted = true;
5082 }
5083
5084 // If none of speculative promotions for NewExts is profitable, rollback
5085 // and save the current extension (I) as the last profitable extension.
5086 if (!NewPromoted) {
5087 TPT.rollback(LastKnownGood);
5088 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005089 continue;
5090 }
5091 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00005092 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005093 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005094 return Promoted;
5095}
5096
Jun Bum Limdee55652017-04-03 19:20:07 +00005097/// Merging redundant sexts when one is dominating the other.
5098bool CodeGenPrepare::mergeSExts(Function &F) {
5099 DominatorTree DT(F);
5100 bool Changed = false;
5101 for (auto &Entry : ValToSExtendedUses) {
5102 SExts &Insts = Entry.second;
5103 SExts CurPts;
5104 for (Instruction *Inst : Insts) {
5105 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5106 Inst->getOperand(0) != Entry.first)
5107 continue;
5108 bool inserted = false;
5109 for (auto &Pt : CurPts) {
5110 if (DT.dominates(Inst, Pt)) {
5111 Pt->replaceAllUsesWith(Inst);
5112 RemovedInsts.insert(Pt);
5113 Pt->removeFromParent();
5114 Pt = Inst;
5115 inserted = true;
5116 Changed = true;
5117 break;
5118 }
5119 if (!DT.dominates(Pt, Inst))
5120 // Give up if we need to merge in a common dominator as the
5121 // expermients show it is not profitable.
5122 continue;
5123 Inst->replaceAllUsesWith(Pt);
5124 RemovedInsts.insert(Inst);
5125 Inst->removeFromParent();
5126 inserted = true;
5127 Changed = true;
5128 break;
5129 }
5130 if (!inserted)
5131 CurPts.push_back(Inst);
5132 }
5133 }
5134 return Changed;
5135}
5136
Jun Bum Lim42301012017-03-17 19:05:21 +00005137/// Return true, if an ext(load) can be formed from an extension in
5138/// \p MovedExts.
5139bool CodeGenPrepare::canFormExtLd(
5140 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5141 Instruction *&Inst, bool HasPromoted) {
5142 for (auto *MovedExtInst : MovedExts) {
5143 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5144 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5145 Inst = MovedExtInst;
5146 break;
5147 }
5148 }
5149 if (!LI)
5150 return false;
5151
5152 // If they're already in the same block, there's nothing to do.
5153 // Make the cheap checks first if we did not promote.
5154 // If we promoted, we need to check if it is indeed profitable.
5155 if (!HasPromoted && LI->getParent() == Inst->getParent())
5156 return false;
5157
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005158 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005159}
5160
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005161/// Move a zext or sext fed by a load into the same basic block as the load,
5162/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5163/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005164///
Jun Bum Limdee55652017-04-03 19:20:07 +00005165/// E.g.,
5166/// \code
5167/// %ld = load i32* %addr
5168/// %add = add nuw i32 %ld, 4
5169/// %zext = zext i32 %add to i64
5170// \endcode
5171/// =>
5172/// \code
5173/// %ld = load i32* %addr
5174/// %zext = zext i32 %ld to i64
5175/// %add = add nuw i64 %zext, 4
5176/// \encode
5177/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5178/// allow us to match zext(load i32*) to i64.
5179///
5180/// Also, try to promote the computations used to obtain a sign extended
5181/// value used into memory accesses.
5182/// E.g.,
5183/// \code
5184/// a = add nsw i32 b, 3
5185/// d = sext i32 a to i64
5186/// e = getelementptr ..., i64 d
5187/// \endcode
5188/// =>
5189/// \code
5190/// f = sext i32 b to i64
5191/// a = add nsw i64 f, 3
5192/// e = getelementptr ..., i64 a
5193/// \endcode
5194///
5195/// \p Inst[in/out] the extension may be modified during the process if some
5196/// promotions apply.
5197bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5198 // ExtLoad formation and address type promotion infrastructure requires TLI to
5199 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005200 if (!TLI)
5201 return false;
5202
Jun Bum Limdee55652017-04-03 19:20:07 +00005203 bool AllowPromotionWithoutCommonHeader = false;
5204 /// See if it is an interesting sext operations for the address type
5205 /// promotion before trying to promote it, e.g., the ones with the right
5206 /// type and used in memory accesses.
5207 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5208 *Inst, AllowPromotionWithoutCommonHeader);
5209 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005210 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005211 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005212 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005213 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5214 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005215
Jun Bum Limdee55652017-04-03 19:20:07 +00005216 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005217
Dan Gohman99429a02009-10-16 20:59:35 +00005218 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005219 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005220 Instruction *ExtFedByLoad;
5221
5222 // Try to promote a chain of computation if it allows to form an extended
5223 // load.
5224 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5225 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5226 TPT.commit();
5227 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005228 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005229 // CGP does not check if the zext would be speculatively executed when moved
5230 // to the same basic block as the load. Preserving its original location
5231 // would pessimize the debugging experience, as well as negatively impact
5232 // the quality of sample pgo. We don't want to use "line 0" as that has a
5233 // size cost in the line-table section and logically the zext can be seen as
5234 // part of the load. Therefore we conservatively reuse the same debug
5235 // location for the load and the zext.
5236 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5237 ++NumExtsMoved;
5238 Inst = ExtFedByLoad;
5239 return true;
5240 }
5241
5242 // Continue promoting SExts if known as considerable depending on targets.
5243 if (ATPConsiderable &&
5244 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5245 HasPromoted, TPT, SpeculativelyMovedExts))
5246 return true;
5247
5248 TPT.rollback(LastKnownGood);
5249 return false;
5250}
5251
5252// Perform address type promotion if doing so is profitable.
5253// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5254// instructions that sign extended the same initial value. However, if
5255// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5256// extension is just profitable.
5257bool CodeGenPrepare::performAddressTypePromotion(
5258 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5259 bool HasPromoted, TypePromotionTransaction &TPT,
5260 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5261 bool Promoted = false;
5262 SmallPtrSet<Instruction *, 1> UnhandledExts;
5263 bool AllSeenFirst = true;
5264 for (auto I : SpeculativelyMovedExts) {
5265 Value *HeadOfChain = I->getOperand(0);
5266 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5267 SeenChainsForSExt.find(HeadOfChain);
5268 // If there is an unhandled SExt which has the same header, try to promote
5269 // it as well.
5270 if (AlreadySeen != SeenChainsForSExt.end()) {
5271 if (AlreadySeen->second != nullptr)
5272 UnhandledExts.insert(AlreadySeen->second);
5273 AllSeenFirst = false;
5274 }
5275 }
5276
5277 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5278 SpeculativelyMovedExts.size() == 1)) {
5279 TPT.commit();
5280 if (HasPromoted)
5281 Promoted = true;
5282 for (auto I : SpeculativelyMovedExts) {
5283 Value *HeadOfChain = I->getOperand(0);
5284 SeenChainsForSExt[HeadOfChain] = nullptr;
5285 ValToSExtendedUses[HeadOfChain].push_back(I);
5286 }
5287 // Update Inst as promotion happen.
5288 Inst = SpeculativelyMovedExts.pop_back_val();
5289 } else {
5290 // This is the first chain visited from the header, keep the current chain
5291 // as unhandled. Defer to promote this until we encounter another SExt
5292 // chain derived from the same header.
5293 for (auto I : SpeculativelyMovedExts) {
5294 Value *HeadOfChain = I->getOperand(0);
5295 SeenChainsForSExt[HeadOfChain] = Inst;
5296 }
Dan Gohman99429a02009-10-16 20:59:35 +00005297 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005298 }
Dan Gohman99429a02009-10-16 20:59:35 +00005299
Jun Bum Limdee55652017-04-03 19:20:07 +00005300 if (!AllSeenFirst && !UnhandledExts.empty())
5301 for (auto VisitedSExt : UnhandledExts) {
5302 if (RemovedInsts.count(VisitedSExt))
5303 continue;
5304 TypePromotionTransaction TPT(RemovedInsts);
5305 SmallVector<Instruction *, 1> Exts;
5306 SmallVector<Instruction *, 2> Chains;
5307 Exts.push_back(VisitedSExt);
5308 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5309 TPT.commit();
5310 if (HasPromoted)
5311 Promoted = true;
5312 for (auto I : Chains) {
5313 Value *HeadOfChain = I->getOperand(0);
5314 // Mark this as handled.
5315 SeenChainsForSExt[HeadOfChain] = nullptr;
5316 ValToSExtendedUses[HeadOfChain].push_back(I);
5317 }
5318 }
5319 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005320}
5321
Sanjay Patelfc580a62015-09-21 23:03:16 +00005322bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005323 BasicBlock *DefBB = I->getParent();
5324
Bob Wilsonff714f92010-09-21 21:44:14 +00005325 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005326 // other uses of the source with result of extension.
5327 Value *Src = I->getOperand(0);
5328 if (Src->hasOneUse())
5329 return false;
5330
Evan Cheng2011df42007-12-13 07:50:36 +00005331 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005332 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005333 return false;
5334
Evan Cheng7bc89422007-12-12 00:51:06 +00005335 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005336 // this block.
5337 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005338 return false;
5339
Evan Chengd3d80172007-12-05 23:58:20 +00005340 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005341 for (User *U : I->users()) {
5342 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005343
5344 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005345 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005346 if (UserBB == DefBB) continue;
5347 DefIsLiveOut = true;
5348 break;
5349 }
5350 if (!DefIsLiveOut)
5351 return false;
5352
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005353 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005354 for (User *U : Src->users()) {
5355 Instruction *UI = cast<Instruction>(U);
5356 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005357 if (UserBB == DefBB) continue;
5358 // Be conservative. We don't want this xform to end up introducing
5359 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005360 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005361 return false;
5362 }
5363
Evan Chengd3d80172007-12-05 23:58:20 +00005364 // InsertedTruncs - Only insert one trunc in each block once.
5365 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5366
5367 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005368 for (Use &U : Src->uses()) {
5369 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005370
5371 // Figure out which BB this ext is used in.
5372 BasicBlock *UserBB = User->getParent();
5373 if (UserBB == DefBB) continue;
5374
5375 // Both src and def are live in this block. Rewrite the use.
5376 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5377
5378 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005379 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005380 assert(InsertPt != UserBB->end());
5381 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005382 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005383 }
5384
5385 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005386 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005387 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005388 MadeChange = true;
5389 }
5390
5391 return MadeChange;
5392}
5393
Geoff Berry5256fca2015-11-20 22:34:39 +00005394// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5395// just after the load if the target can fold this into one extload instruction,
5396// with the hope of eliminating some of the other later "and" instructions using
5397// the loaded value. "and"s that are made trivially redundant by the insertion
5398// of the new "and" are removed by this function, while others (e.g. those whose
5399// path from the load goes through a phi) are left for isel to potentially
5400// remove.
5401//
5402// For example:
5403//
5404// b0:
5405// x = load i32
5406// ...
5407// b1:
5408// y = and x, 0xff
5409// z = use y
5410//
5411// becomes:
5412//
5413// b0:
5414// x = load i32
5415// x' = and x, 0xff
5416// ...
5417// b1:
5418// z = use x'
5419//
5420// whereas:
5421//
5422// b0:
5423// x1 = load i32
5424// ...
5425// b1:
5426// x2 = load i32
5427// ...
5428// b2:
5429// x = phi x1, x2
5430// y = and x, 0xff
5431//
5432// becomes (after a call to optimizeLoadExt for each load):
5433//
5434// b0:
5435// x1 = load i32
5436// x1' = and x1, 0xff
5437// ...
5438// b1:
5439// x2 = load i32
5440// x2' = and x2, 0xff
5441// ...
5442// b2:
5443// x = phi x1', x2'
5444// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005445bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005446 if (!Load->isSimple() ||
5447 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5448 return false;
5449
Geoff Berry5d534b62017-02-21 18:53:14 +00005450 // Skip loads we've already transformed.
5451 if (Load->hasOneUse() &&
5452 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5453 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005454
5455 // Look at all uses of Load, looking through phis, to determine how many bits
5456 // of the loaded value are needed.
5457 SmallVector<Instruction *, 8> WorkList;
5458 SmallPtrSet<Instruction *, 16> Visited;
5459 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5460 for (auto *U : Load->users())
5461 WorkList.push_back(cast<Instruction>(U));
5462
5463 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5464 unsigned BitWidth = LoadResultVT.getSizeInBits();
5465 APInt DemandBits(BitWidth, 0);
5466 APInt WidestAndBits(BitWidth, 0);
5467
5468 while (!WorkList.empty()) {
5469 Instruction *I = WorkList.back();
5470 WorkList.pop_back();
5471
5472 // Break use-def graph loops.
5473 if (!Visited.insert(I).second)
5474 continue;
5475
5476 // For a PHI node, push all of its users.
5477 if (auto *Phi = dyn_cast<PHINode>(I)) {
5478 for (auto *U : Phi->users())
5479 WorkList.push_back(cast<Instruction>(U));
5480 continue;
5481 }
5482
5483 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005484 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005485 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5486 if (!AndC)
5487 return false;
5488 APInt AndBits = AndC->getValue();
5489 DemandBits |= AndBits;
5490 // Keep track of the widest and mask we see.
5491 if (AndBits.ugt(WidestAndBits))
5492 WidestAndBits = AndBits;
5493 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5494 AndsToMaybeRemove.push_back(I);
5495 break;
5496 }
5497
Eugene Zelenko900b6332017-08-29 22:32:07 +00005498 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005499 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5500 if (!ShlC)
5501 return false;
5502 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005503 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005504 break;
5505 }
5506
Eugene Zelenko900b6332017-08-29 22:32:07 +00005507 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005508 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5509 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005510 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005511 break;
5512 }
5513
5514 default:
5515 return false;
5516 }
5517 }
5518
5519 uint32_t ActiveBits = DemandBits.getActiveBits();
5520 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5521 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5522 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5523 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5524 // followed by an AND.
5525 // TODO: Look into removing this restriction by fixing backends to either
5526 // return false for isLoadExtLegal for i1 or have them select this pattern to
5527 // a single instruction.
5528 //
5529 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5530 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005531 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005532 WidestAndBits != DemandBits)
5533 return false;
5534
5535 LLVMContext &Ctx = Load->getType()->getContext();
5536 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5537 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5538
5539 // Reject cases that won't be matched as extloads.
5540 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5541 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5542 return false;
5543
5544 IRBuilder<> Builder(Load->getNextNode());
5545 auto *NewAnd = dyn_cast<Instruction>(
5546 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005547 // Mark this instruction as "inserted by CGP", so that other
5548 // optimizations don't touch it.
5549 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005550
5551 // Replace all uses of load with new and (except for the use of load in the
5552 // new and itself).
5553 Load->replaceAllUsesWith(NewAnd);
5554 NewAnd->setOperand(0, Load);
5555
5556 // Remove any and instructions that are now redundant.
5557 for (auto *And : AndsToMaybeRemove)
5558 // Check that the and mask is the same as the one we decided to put on the
5559 // new and.
5560 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5561 And->replaceAllUsesWith(NewAnd);
5562 if (&*CurInstIterator == And)
5563 CurInstIterator = std::next(And->getIterator());
5564 And->eraseFromParent();
5565 ++NumAndUses;
5566 }
5567
5568 ++NumAndsAdded;
5569 return true;
5570}
5571
Sanjay Patel69a50a12015-10-19 21:59:12 +00005572/// Check if V (an operand of a select instruction) is an expensive instruction
5573/// that is only used once.
5574static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5575 auto *I = dyn_cast<Instruction>(V);
5576 // If it's safe to speculatively execute, then it should not have side
5577 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005578 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5579 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005580}
5581
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005582/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005583static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005584 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005585 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005586 // If even a predictable select is cheap, then a branch can't be cheaper.
5587 if (!TLI->isPredictableSelectExpensive())
5588 return false;
5589
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005590 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005591 // whether a select is better represented as a branch.
5592
5593 // If metadata tells us that the select condition is obviously predictable,
5594 // then we want to replace the select with a branch.
5595 uint64_t TrueWeight, FalseWeight;
5596 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5597 uint64_t Max = std::max(TrueWeight, FalseWeight);
5598 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005599 if (Sum != 0) {
5600 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5601 if (Probability > TLI->getPredictableBranchThreshold())
5602 return true;
5603 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005604 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005605
5606 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5607
Sanjay Patel4e652762015-09-28 22:14:51 +00005608 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5609 // comparison condition. If the compare has more than one use, there's
5610 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005611 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005612 return false;
5613
Sanjay Patel69a50a12015-10-19 21:59:12 +00005614 // If either operand of the select is expensive and only needed on one side
5615 // of the select, we should form a branch.
5616 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5617 sinkSelectOperand(TTI, SI->getFalseValue()))
5618 return true;
5619
5620 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005621}
5622
Dehao Chen9bbb9412016-09-12 20:23:28 +00005623/// If \p isTrue is true, return the true value of \p SI, otherwise return
5624/// false value of \p SI. If the true/false value of \p SI is defined by any
5625/// select instructions in \p Selects, look through the defining select
5626/// instruction until the true/false value is not defined in \p Selects.
5627static Value *getTrueOrFalseValue(
5628 SelectInst *SI, bool isTrue,
5629 const SmallPtrSet<const Instruction *, 2> &Selects) {
5630 Value *V;
5631
5632 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5633 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005634 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005635 "The condition of DefSI does not match with SI");
5636 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5637 }
5638 return V;
5639}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005640
Nadav Rotem9d832022012-09-02 12:10:19 +00005641/// If we have a SelectInst that will likely profit from branch prediction,
5642/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005643bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005644 // Find all consecutive select instructions that share the same condition.
5645 SmallVector<SelectInst *, 2> ASI;
5646 ASI.push_back(SI);
5647 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5648 It != SI->getParent()->end(); ++It) {
5649 SelectInst *I = dyn_cast<SelectInst>(&*It);
5650 if (I && SI->getCondition() == I->getCondition()) {
5651 ASI.push_back(I);
5652 } else {
5653 break;
5654 }
5655 }
5656
5657 SelectInst *LastSI = ASI.back();
5658 // Increment the current iterator to skip all the rest of select instructions
5659 // because they will be either "not lowered" or "all lowered" to branch.
5660 CurInstIterator = std::next(LastSI->getIterator());
5661
Nadav Rotem9d832022012-09-02 12:10:19 +00005662 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5663
5664 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005665 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5666 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005667 return false;
5668
Nadav Rotem9d832022012-09-02 12:10:19 +00005669 TargetLowering::SelectSupportKind SelectKind;
5670 if (VectorCond)
5671 SelectKind = TargetLowering::VectorMaskSelect;
5672 else if (SI->getType()->isVectorTy())
5673 SelectKind = TargetLowering::ScalarCondVectorVal;
5674 else
5675 SelectKind = TargetLowering::ScalarValSelect;
5676
Sanjay Pateld66607b2016-04-26 17:11:17 +00005677 if (TLI->isSelectSupported(SelectKind) &&
5678 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5679 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005680
5681 ModifiedDT = true;
5682
Sanjay Patel69a50a12015-10-19 21:59:12 +00005683 // Transform a sequence like this:
5684 // start:
5685 // %cmp = cmp uge i32 %a, %b
5686 // %sel = select i1 %cmp, i32 %c, i32 %d
5687 //
5688 // Into:
5689 // start:
5690 // %cmp = cmp uge i32 %a, %b
5691 // br i1 %cmp, label %select.true, label %select.false
5692 // select.true:
5693 // br label %select.end
5694 // select.false:
5695 // br label %select.end
5696 // select.end:
5697 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5698 //
5699 // In addition, we may sink instructions that produce %c or %d from
5700 // the entry block into the destination(s) of the new branch.
5701 // If the true or false blocks do not contain a sunken instruction, that
5702 // block and its branch may be optimized away. In that case, one side of the
5703 // first branch will point directly to select.end, and the corresponding PHI
5704 // predecessor block will be the start block.
5705
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005706 // First, we split the block containing the select into 2 blocks.
5707 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005708 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005709 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005710
Sanjay Patel69a50a12015-10-19 21:59:12 +00005711 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005712 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005713
5714 // These are the new basic blocks for the conditional branch.
5715 // At least one will become an actual new basic block.
5716 BasicBlock *TrueBlock = nullptr;
5717 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005718 BranchInst *TrueBranch = nullptr;
5719 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005720
5721 // Sink expensive instructions into the conditional blocks to avoid executing
5722 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005723 for (SelectInst *SI : ASI) {
5724 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5725 if (TrueBlock == nullptr) {
5726 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5727 EndBlock->getParent(), EndBlock);
5728 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5729 }
5730 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5731 TrueInst->moveBefore(TrueBranch);
5732 }
5733 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5734 if (FalseBlock == nullptr) {
5735 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5736 EndBlock->getParent(), EndBlock);
5737 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5738 }
5739 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5740 FalseInst->moveBefore(FalseBranch);
5741 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005742 }
5743
5744 // If there was nothing to sink, then arbitrarily choose the 'false' side
5745 // for a new input value to the PHI.
5746 if (TrueBlock == FalseBlock) {
5747 assert(TrueBlock == nullptr &&
5748 "Unexpected basic block transform while optimizing select");
5749
5750 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5751 EndBlock->getParent(), EndBlock);
5752 BranchInst::Create(EndBlock, FalseBlock);
5753 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005754
5755 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005756 // If we did not create a new block for one of the 'true' or 'false' paths
5757 // of the condition, it means that side of the branch goes to the end block
5758 // directly and the path originates from the start block from the point of
5759 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005760 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005761 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005762 TT = EndBlock;
5763 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005764 TrueBlock = StartBlock;
5765 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005766 TT = TrueBlock;
5767 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005768 FalseBlock = StartBlock;
5769 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005770 TT = TrueBlock;
5771 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005772 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005773 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005774
Dehao Chen9bbb9412016-09-12 20:23:28 +00005775 SmallPtrSet<const Instruction *, 2> INS;
5776 INS.insert(ASI.begin(), ASI.end());
5777 // Use reverse iterator because later select may use the value of the
5778 // earlier select, and we need to propagate value through earlier select
5779 // to get the PHI operand.
5780 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5781 SelectInst *SI = *It;
5782 // The select itself is replaced with a PHI Node.
5783 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5784 PN->takeName(SI);
5785 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5786 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005787
Dehao Chen9bbb9412016-09-12 20:23:28 +00005788 SI->replaceAllUsesWith(PN);
5789 SI->eraseFromParent();
5790 INS.erase(SI);
5791 ++NumSelectsExpanded;
5792 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005793
5794 // Instruct OptimizeBlock to skip to the next block.
5795 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005796 return true;
5797}
5798
Benjamin Kramer573ff362014-03-01 17:24:40 +00005799static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005800 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5801 int SplatElem = -1;
5802 for (unsigned i = 0; i < Mask.size(); ++i) {
5803 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5804 return false;
5805 SplatElem = Mask[i];
5806 }
5807
5808 return true;
5809}
5810
5811/// Some targets have expensive vector shifts if the lanes aren't all the same
5812/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5813/// it's often worth sinking a shufflevector splat down to its use so that
5814/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005815bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005816 BasicBlock *DefBB = SVI->getParent();
5817
5818 // Only do this xform if variable vector shifts are particularly expensive.
5819 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5820 return false;
5821
5822 // We only expect better codegen by sinking a shuffle if we can recognise a
5823 // constant splat.
5824 if (!isBroadcastShuffle(SVI))
5825 return false;
5826
5827 // InsertedShuffles - Only insert a shuffle in each block once.
5828 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5829
5830 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005831 for (User *U : SVI->users()) {
5832 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005833
5834 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005835 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005836 if (UserBB == DefBB) continue;
5837
5838 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005839 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005840
5841 // Everything checks out, sink the shuffle if the user's block doesn't
5842 // already have a copy.
5843 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5844
5845 if (!InsertedShuffle) {
5846 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005847 assert(InsertPt != UserBB->end());
5848 InsertedShuffle =
5849 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5850 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005851 }
5852
Chandler Carruthcdf47882014-03-09 03:16:01 +00005853 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005854 MadeChange = true;
5855 }
5856
5857 // If we removed all uses, nuke the shuffle.
5858 if (SVI->use_empty()) {
5859 SVI->eraseFromParent();
5860 MadeChange = true;
5861 }
5862
5863 return MadeChange;
5864}
5865
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005866bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5867 if (!TLI || !DL)
5868 return false;
5869
5870 Value *Cond = SI->getCondition();
5871 Type *OldType = Cond->getType();
5872 LLVMContext &Context = Cond->getContext();
5873 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5874 unsigned RegWidth = RegType.getSizeInBits();
5875
5876 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5877 return false;
5878
5879 // If the register width is greater than the type width, expand the condition
5880 // of the switch instruction and each case constant to the width of the
5881 // register. By widening the type of the switch condition, subsequent
5882 // comparisons (for case comparisons) will not need to be extended to the
5883 // preferred register width, so we will potentially eliminate N-1 extends,
5884 // where N is the number of cases in the switch.
5885 auto *NewType = Type::getIntNTy(Context, RegWidth);
5886
5887 // Zero-extend the switch condition and case constants unless the switch
5888 // condition is a function argument that is already being sign-extended.
5889 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5890 // everything instead.
5891 Instruction::CastOps ExtType = Instruction::ZExt;
5892 if (auto *Arg = dyn_cast<Argument>(Cond))
5893 if (Arg->hasSExtAttr())
5894 ExtType = Instruction::SExt;
5895
5896 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5897 ExtInst->insertBefore(SI);
5898 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005899 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005900 APInt NarrowConst = Case.getCaseValue()->getValue();
5901 APInt WideConst = (ExtType == Instruction::ZExt) ?
5902 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5903 Case.setValue(ConstantInt::get(Context, WideConst));
5904 }
5905
5906 return true;
5907}
5908
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005909
Quentin Colombetc32615d2014-10-31 17:52:53 +00005910namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005911
Quentin Colombetc32615d2014-10-31 17:52:53 +00005912/// \brief Helper class to promote a scalar operation to a vector one.
5913/// This class is used to move downward extractelement transition.
5914/// E.g.,
5915/// a = vector_op <2 x i32>
5916/// b = extractelement <2 x i32> a, i32 0
5917/// c = scalar_op b
5918/// store c
5919///
5920/// =>
5921/// a = vector_op <2 x i32>
5922/// c = vector_op a (equivalent to scalar_op on the related lane)
5923/// * d = extractelement <2 x i32> c, i32 0
5924/// * store d
5925/// Assuming both extractelement and store can be combine, we get rid of the
5926/// transition.
5927class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005928 /// DataLayout associated with the current module.
5929 const DataLayout &DL;
5930
Quentin Colombetc32615d2014-10-31 17:52:53 +00005931 /// Used to perform some checks on the legality of vector operations.
5932 const TargetLowering &TLI;
5933
5934 /// Used to estimated the cost of the promoted chain.
5935 const TargetTransformInfo &TTI;
5936
5937 /// The transition being moved downwards.
5938 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005939
Quentin Colombetc32615d2014-10-31 17:52:53 +00005940 /// The sequence of instructions to be promoted.
5941 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005942
Quentin Colombetc32615d2014-10-31 17:52:53 +00005943 /// Cost of combining a store and an extract.
5944 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005945
Quentin Colombetc32615d2014-10-31 17:52:53 +00005946 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005947 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005948
5949 /// \brief The instruction that represents the current end of the transition.
5950 /// Since we are faking the promotion until we reach the end of the chain
5951 /// of computation, we need a way to get the current end of the transition.
5952 Instruction *getEndOfTransition() const {
5953 if (InstsToBePromoted.empty())
5954 return Transition;
5955 return InstsToBePromoted.back();
5956 }
5957
5958 /// \brief Return the index of the original value in the transition.
5959 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5960 /// c, is at index 0.
5961 unsigned getTransitionOriginalValueIdx() const {
5962 assert(isa<ExtractElementInst>(Transition) &&
5963 "Other kind of transitions are not supported yet");
5964 return 0;
5965 }
5966
5967 /// \brief Return the index of the index in the transition.
5968 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5969 /// is at index 1.
5970 unsigned getTransitionIdx() const {
5971 assert(isa<ExtractElementInst>(Transition) &&
5972 "Other kind of transitions are not supported yet");
5973 return 1;
5974 }
5975
5976 /// \brief Get the type of the transition.
5977 /// This is the type of the original value.
5978 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5979 /// transition is <2 x i32>.
5980 Type *getTransitionType() const {
5981 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5982 }
5983
5984 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5985 /// I.e., we have the following sequence:
5986 /// Def = Transition <ty1> a to <ty2>
5987 /// b = ToBePromoted <ty2> Def, ...
5988 /// =>
5989 /// b = ToBePromoted <ty1> a, ...
5990 /// Def = Transition <ty1> ToBePromoted to <ty2>
5991 void promoteImpl(Instruction *ToBePromoted);
5992
5993 /// \brief Check whether or not it is profitable to promote all the
5994 /// instructions enqueued to be promoted.
5995 bool isProfitableToPromote() {
5996 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5997 unsigned Index = isa<ConstantInt>(ValIdx)
5998 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5999 : -1;
6000 Type *PromotedType = getTransitionType();
6001
6002 StoreInst *ST = cast<StoreInst>(CombineInst);
6003 unsigned AS = ST->getPointerAddressSpace();
6004 unsigned Align = ST->getAlignment();
6005 // Check if this store is supported.
6006 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00006007 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
6008 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006009 // If this is not supported, there is no way we can combine
6010 // the extract with the store.
6011 return false;
6012 }
6013
6014 // The scalar chain of computation has to pay for the transition
6015 // scalar to vector.
6016 // The vector chain has to account for the combining cost.
6017 uint64_t ScalarCost =
6018 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
6019 uint64_t VectorCost = StoreExtractCombineCost;
6020 for (const auto &Inst : InstsToBePromoted) {
6021 // Compute the cost.
6022 // By construction, all instructions being promoted are arithmetic ones.
6023 // Moreover, one argument is a constant that can be viewed as a splat
6024 // constant.
6025 Value *Arg0 = Inst->getOperand(0);
6026 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
6027 isa<ConstantFP>(Arg0);
6028 TargetTransformInfo::OperandValueKind Arg0OVK =
6029 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6030 : TargetTransformInfo::OK_AnyValue;
6031 TargetTransformInfo::OperandValueKind Arg1OVK =
6032 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6033 : TargetTransformInfo::OK_AnyValue;
6034 ScalarCost += TTI.getArithmeticInstrCost(
6035 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
6036 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
6037 Arg0OVK, Arg1OVK);
6038 }
6039 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
6040 << ScalarCost << "\nVector: " << VectorCost << '\n');
6041 return ScalarCost > VectorCost;
6042 }
6043
6044 /// \brief Generate a constant vector with \p Val with the same
6045 /// number of elements as the transition.
6046 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00006047 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006048 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
6049 /// otherwise we generate a vector with as many undef as possible:
6050 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
6051 /// used at the index of the extract.
6052 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006053 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006054 if (!UseSplat) {
6055 // If we cannot determine where the constant must be, we have to
6056 // use a splat constant.
6057 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
6058 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6059 ExtractIdx = CstVal->getSExtValue();
6060 else
6061 UseSplat = true;
6062 }
6063
6064 unsigned End = getTransitionType()->getVectorNumElements();
6065 if (UseSplat)
6066 return ConstantVector::getSplat(End, Val);
6067
6068 SmallVector<Constant *, 4> ConstVec;
6069 UndefValue *UndefVal = UndefValue::get(Val->getType());
6070 for (unsigned Idx = 0; Idx != End; ++Idx) {
6071 if (Idx == ExtractIdx)
6072 ConstVec.push_back(Val);
6073 else
6074 ConstVec.push_back(UndefVal);
6075 }
6076 return ConstantVector::get(ConstVec);
6077 }
6078
6079 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
6080 /// in \p Use can trigger undefined behavior.
6081 static bool canCauseUndefinedBehavior(const Instruction *Use,
6082 unsigned OperandIdx) {
6083 // This is not safe to introduce undef when the operand is on
6084 // the right hand side of a division-like instruction.
6085 if (OperandIdx != 1)
6086 return false;
6087 switch (Use->getOpcode()) {
6088 default:
6089 return false;
6090 case Instruction::SDiv:
6091 case Instruction::UDiv:
6092 case Instruction::SRem:
6093 case Instruction::URem:
6094 return true;
6095 case Instruction::FDiv:
6096 case Instruction::FRem:
6097 return !Use->hasNoNaNs();
6098 }
6099 llvm_unreachable(nullptr);
6100 }
6101
6102public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006103 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6104 const TargetTransformInfo &TTI, Instruction *Transition,
6105 unsigned CombineCost)
6106 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006107 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006108 assert(Transition && "Do not know how to promote null");
6109 }
6110
6111 /// \brief Check if we can promote \p ToBePromoted to \p Type.
6112 bool canPromote(const Instruction *ToBePromoted) const {
6113 // We could support CastInst too.
6114 return isa<BinaryOperator>(ToBePromoted);
6115 }
6116
6117 /// \brief Check if it is profitable to promote \p ToBePromoted
6118 /// by moving downward the transition through.
6119 bool shouldPromote(const Instruction *ToBePromoted) const {
6120 // Promote only if all the operands can be statically expanded.
6121 // Indeed, we do not want to introduce any new kind of transitions.
6122 for (const Use &U : ToBePromoted->operands()) {
6123 const Value *Val = U.get();
6124 if (Val == getEndOfTransition()) {
6125 // If the use is a division and the transition is on the rhs,
6126 // we cannot promote the operation, otherwise we may create a
6127 // division by zero.
6128 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6129 return false;
6130 continue;
6131 }
6132 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6133 !isa<ConstantFP>(Val))
6134 return false;
6135 }
6136 // Check that the resulting operation is legal.
6137 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6138 if (!ISDOpcode)
6139 return false;
6140 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006141 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006142 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006143 }
6144
6145 /// \brief Check whether or not \p Use can be combined
6146 /// with the transition.
6147 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6148 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6149
6150 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
6151 void enqueueForPromotion(Instruction *ToBePromoted) {
6152 InstsToBePromoted.push_back(ToBePromoted);
6153 }
6154
6155 /// \brief Set the instruction that will be combined with the transition.
6156 void recordCombineInstruction(Instruction *ToBeCombined) {
6157 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6158 CombineInst = ToBeCombined;
6159 }
6160
6161 /// \brief Promote all the instructions enqueued for promotion if it is
6162 /// is profitable.
6163 /// \return True if the promotion happened, false otherwise.
6164 bool promote() {
6165 // Check if there is something to promote.
6166 // Right now, if we do not have anything to combine with,
6167 // we assume the promotion is not profitable.
6168 if (InstsToBePromoted.empty() || !CombineInst)
6169 return false;
6170
6171 // Check cost.
6172 if (!StressStoreExtract && !isProfitableToPromote())
6173 return false;
6174
6175 // Promote.
6176 for (auto &ToBePromoted : InstsToBePromoted)
6177 promoteImpl(ToBePromoted);
6178 InstsToBePromoted.clear();
6179 return true;
6180 }
6181};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006182
6183} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006184
6185void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6186 // At this point, we know that all the operands of ToBePromoted but Def
6187 // can be statically promoted.
6188 // For Def, we need to use its parameter in ToBePromoted:
6189 // b = ToBePromoted ty1 a
6190 // Def = Transition ty1 b to ty2
6191 // Move the transition down.
6192 // 1. Replace all uses of the promoted operation by the transition.
6193 // = ... b => = ... Def.
6194 assert(ToBePromoted->getType() == Transition->getType() &&
6195 "The type of the result of the transition does not match "
6196 "the final type");
6197 ToBePromoted->replaceAllUsesWith(Transition);
6198 // 2. Update the type of the uses.
6199 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6200 Type *TransitionTy = getTransitionType();
6201 ToBePromoted->mutateType(TransitionTy);
6202 // 3. Update all the operands of the promoted operation with promoted
6203 // operands.
6204 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6205 for (Use &U : ToBePromoted->operands()) {
6206 Value *Val = U.get();
6207 Value *NewVal = nullptr;
6208 if (Val == Transition)
6209 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6210 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6211 isa<ConstantFP>(Val)) {
6212 // Use a splat constant if it is not safe to use undef.
6213 NewVal = getConstantVector(
6214 cast<Constant>(Val),
6215 isa<UndefValue>(Val) ||
6216 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6217 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006218 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6219 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006220 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6221 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006222 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006223 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6224}
6225
6226/// Some targets can do store(extractelement) with one instruction.
6227/// Try to push the extractelement towards the stores when the target
6228/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006229bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006230 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006231 if (DisableStoreExtract || !TLI ||
6232 (!StressStoreExtract &&
6233 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6234 Inst->getOperand(1), CombineCost)))
6235 return false;
6236
6237 // At this point we know that Inst is a vector to scalar transition.
6238 // Try to move it down the def-use chain, until:
6239 // - We can combine the transition with its single use
6240 // => we got rid of the transition.
6241 // - We escape the current basic block
6242 // => we would need to check that we are moving it at a cheaper place and
6243 // we do not do that for now.
6244 BasicBlock *Parent = Inst->getParent();
6245 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006246 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006247 // If the transition has more than one use, assume this is not going to be
6248 // beneficial.
6249 while (Inst->hasOneUse()) {
6250 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
6251 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
6252
6253 if (ToBePromoted->getParent() != Parent) {
6254 DEBUG(dbgs() << "Instruction to promote is in a different block ("
6255 << ToBePromoted->getParent()->getName()
6256 << ") than the transition (" << Parent->getName() << ").\n");
6257 return false;
6258 }
6259
6260 if (VPH.canCombine(ToBePromoted)) {
6261 DEBUG(dbgs() << "Assume " << *Inst << '\n'
6262 << "will be combined with: " << *ToBePromoted << '\n');
6263 VPH.recordCombineInstruction(ToBePromoted);
6264 bool Changed = VPH.promote();
6265 NumStoreExtractExposed += Changed;
6266 return Changed;
6267 }
6268
6269 DEBUG(dbgs() << "Try promoting.\n");
6270 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6271 return false;
6272
6273 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
6274
6275 VPH.enqueueForPromotion(ToBePromoted);
6276 Inst = ToBePromoted;
6277 }
6278 return false;
6279}
6280
Wei Mia2f0b592016-12-22 19:44:45 +00006281/// For the instruction sequence of store below, F and I values
6282/// are bundled together as an i64 value before being stored into memory.
6283/// Sometimes it is more efficent to generate separate stores for F and I,
6284/// which can remove the bitwise instructions or sink them to colder places.
6285///
6286/// (store (or (zext (bitcast F to i32) to i64),
6287/// (shl (zext I to i64), 32)), addr) -->
6288/// (store F, addr) and (store I, addr+4)
6289///
6290/// Similarly, splitting for other merged store can also be beneficial, like:
6291/// For pair of {i32, i32}, i64 store --> two i32 stores.
6292/// For pair of {i32, i16}, i64 store --> two i32 stores.
6293/// For pair of {i16, i16}, i32 store --> two i16 stores.
6294/// For pair of {i16, i8}, i32 store --> two i16 stores.
6295/// For pair of {i8, i8}, i16 store --> two i8 stores.
6296///
6297/// We allow each target to determine specifically which kind of splitting is
6298/// supported.
6299///
6300/// The store patterns are commonly seen from the simple code snippet below
6301/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6302/// void goo(const std::pair<int, float> &);
6303/// hoo() {
6304/// ...
6305/// goo(std::make_pair(tmp, ftmp));
6306/// ...
6307/// }
6308///
6309/// Although we already have similar splitting in DAG Combine, we duplicate
6310/// it in CodeGenPrepare to catch the case in which pattern is across
6311/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6312/// during code expansion.
6313static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6314 const TargetLowering &TLI) {
6315 // Handle simple but common cases only.
6316 Type *StoreType = SI.getValueOperand()->getType();
6317 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6318 DL.getTypeSizeInBits(StoreType) == 0)
6319 return false;
6320
6321 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6322 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6323 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6324 DL.getTypeSizeInBits(SplitStoreType))
6325 return false;
6326
6327 // Match the following patterns:
6328 // (store (or (zext LValue to i64),
6329 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6330 // or
6331 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6332 // (zext LValue to i64),
6333 // Expect both operands of OR and the first operand of SHL have only
6334 // one use.
6335 Value *LValue, *HValue;
6336 if (!match(SI.getValueOperand(),
6337 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6338 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6339 m_SpecificInt(HalfValBitSize))))))
6340 return false;
6341
6342 // Check LValue and HValue are int with size less or equal than 32.
6343 if (!LValue->getType()->isIntegerTy() ||
6344 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6345 !HValue->getType()->isIntegerTy() ||
6346 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6347 return false;
6348
6349 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6350 // as the input of target query.
6351 auto *LBC = dyn_cast<BitCastInst>(LValue);
6352 auto *HBC = dyn_cast<BitCastInst>(HValue);
6353 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6354 : EVT::getEVT(LValue->getType());
6355 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6356 : EVT::getEVT(HValue->getType());
6357 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6358 return false;
6359
6360 // Start to split store.
6361 IRBuilder<> Builder(SI.getContext());
6362 Builder.SetInsertPoint(&SI);
6363
6364 // If LValue/HValue is a bitcast in another BB, create a new one in current
6365 // BB so it may be merged with the splitted stores by dag combiner.
6366 if (LBC && LBC->getParent() != SI.getParent())
6367 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6368 if (HBC && HBC->getParent() != SI.getParent())
6369 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6370
6371 auto CreateSplitStore = [&](Value *V, bool Upper) {
6372 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6373 Value *Addr = Builder.CreateBitCast(
6374 SI.getOperand(1),
6375 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6376 if (Upper)
6377 Addr = Builder.CreateGEP(
6378 SplitStoreType, Addr,
6379 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6380 Builder.CreateAlignedStore(
6381 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6382 };
6383
6384 CreateSplitStore(LValue, false);
6385 CreateSplitStore(HValue, true);
6386
6387 // Delete the old store.
6388 SI.eraseFromParent();
6389 return true;
6390}
6391
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006392// Return true if the GEP has two operands, the first operand is of a sequential
6393// type, and the second operand is a constant.
6394static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6395 gep_type_iterator I = gep_type_begin(*GEP);
6396 return GEP->getNumOperands() == 2 &&
6397 I.isSequential() &&
6398 isa<ConstantInt>(GEP->getOperand(1));
6399}
6400
6401// Try unmerging GEPs to reduce liveness interference (register pressure) across
6402// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6403// reducing liveness interference across those edges benefits global register
6404// allocation. Currently handles only certain cases.
6405//
6406// For example, unmerge %GEPI and %UGEPI as below.
6407//
6408// ---------- BEFORE ----------
6409// SrcBlock:
6410// ...
6411// %GEPIOp = ...
6412// ...
6413// %GEPI = gep %GEPIOp, Idx
6414// ...
6415// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6416// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6417// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6418// %UGEPI)
6419//
6420// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6421// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6422// ...
6423//
6424// DstBi:
6425// ...
6426// %UGEPI = gep %GEPIOp, UIdx
6427// ...
6428// ---------------------------
6429//
6430// ---------- AFTER ----------
6431// SrcBlock:
6432// ... (same as above)
6433// (* %GEPI is still alive on the indirectbr edges)
6434// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6435// unmerging)
6436// ...
6437//
6438// DstBi:
6439// ...
6440// %UGEPI = gep %GEPI, (UIdx-Idx)
6441// ...
6442// ---------------------------
6443//
6444// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6445// no longer alive on them.
6446//
6447// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6448// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6449// not to disable further simplications and optimizations as a result of GEP
6450// merging.
6451//
6452// Note this unmerging may increase the length of the data flow critical path
6453// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6454// between the register pressure and the length of data-flow critical
6455// path. Restricting this to the uncommon IndirectBr case would minimize the
6456// impact of potentially longer critical path, if any, and the impact on compile
6457// time.
6458static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6459 const TargetTransformInfo *TTI) {
6460 BasicBlock *SrcBlock = GEPI->getParent();
6461 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6462 // (non-IndirectBr) cases exit early here.
6463 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6464 return false;
6465 // Check that GEPI is a simple gep with a single constant index.
6466 if (!GEPSequentialConstIndexed(GEPI))
6467 return false;
6468 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6469 // Check that GEPI is a cheap one.
6470 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6471 > TargetTransformInfo::TCC_Basic)
6472 return false;
6473 Value *GEPIOp = GEPI->getOperand(0);
6474 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6475 if (!isa<Instruction>(GEPIOp))
6476 return false;
6477 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6478 if (GEPIOpI->getParent() != SrcBlock)
6479 return false;
6480 // Check that GEP is used outside the block, meaning it's alive on the
6481 // IndirectBr edge(s).
6482 if (find_if(GEPI->users(), [&](User *Usr) {
6483 if (auto *I = dyn_cast<Instruction>(Usr)) {
6484 if (I->getParent() != SrcBlock) {
6485 return true;
6486 }
6487 }
6488 return false;
6489 }) == GEPI->users().end())
6490 return false;
6491 // The second elements of the GEP chains to be unmerged.
6492 std::vector<GetElementPtrInst *> UGEPIs;
6493 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6494 // on IndirectBr edges.
6495 for (User *Usr : GEPIOp->users()) {
6496 if (Usr == GEPI) continue;
6497 // Check if Usr is an Instruction. If not, give up.
6498 if (!isa<Instruction>(Usr))
6499 return false;
6500 auto *UI = cast<Instruction>(Usr);
6501 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6502 if (UI->getParent() == SrcBlock)
6503 continue;
6504 // Check if Usr is a GEP. If not, give up.
6505 if (!isa<GetElementPtrInst>(Usr))
6506 return false;
6507 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6508 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6509 // the pointer operand to it. If so, record it in the vector. If not, give
6510 // up.
6511 if (!GEPSequentialConstIndexed(UGEPI))
6512 return false;
6513 if (UGEPI->getOperand(0) != GEPIOp)
6514 return false;
6515 if (GEPIIdx->getType() !=
6516 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6517 return false;
6518 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6519 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6520 > TargetTransformInfo::TCC_Basic)
6521 return false;
6522 UGEPIs.push_back(UGEPI);
6523 }
6524 if (UGEPIs.size() == 0)
6525 return false;
6526 // Check the materializing cost of (Uidx-Idx).
6527 for (GetElementPtrInst *UGEPI : UGEPIs) {
6528 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6529 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6530 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6531 if (ImmCost > TargetTransformInfo::TCC_Basic)
6532 return false;
6533 }
6534 // Now unmerge between GEPI and UGEPIs.
6535 for (GetElementPtrInst *UGEPI : UGEPIs) {
6536 UGEPI->setOperand(0, GEPI);
6537 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6538 Constant *NewUGEPIIdx =
6539 ConstantInt::get(GEPIIdx->getType(),
6540 UGEPIIdx->getValue() - GEPIIdx->getValue());
6541 UGEPI->setOperand(1, NewUGEPIIdx);
6542 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6543 // inbounds to avoid UB.
6544 if (!GEPI->isInBounds()) {
6545 UGEPI->setIsInBounds(false);
6546 }
6547 }
6548 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6549 // alive on IndirectBr edges).
6550 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6551 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6552 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6553 return true;
6554}
6555
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006556bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006557 // Bail out if we inserted the instruction to prevent optimizations from
6558 // stepping on each other's toes.
6559 if (InsertedInsts.count(I))
6560 return false;
6561
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006562 if (PHINode *P = dyn_cast<PHINode>(I)) {
6563 // It is possible for very late stage optimizations (such as SimplifyCFG)
6564 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6565 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006566 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006567 P->replaceAllUsesWith(V);
6568 P->eraseFromParent();
6569 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006570 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006571 }
Chris Lattneree588de2011-01-15 07:29:01 +00006572 return false;
6573 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006574
Chris Lattneree588de2011-01-15 07:29:01 +00006575 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006576 // If the source of the cast is a constant, then this should have
6577 // already been constant folded. The only reason NOT to constant fold
6578 // it is if something (e.g. LSR) was careful to place the constant
6579 // evaluation in a block other than then one that uses it (e.g. to hoist
6580 // the address of globals out of a loop). If this is the case, we don't
6581 // want to forward-subst the cast.
6582 if (isa<Constant>(CI->getOperand(0)))
6583 return false;
6584
Mehdi Amini44ede332015-07-09 02:09:04 +00006585 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006586 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006587
Chris Lattneree588de2011-01-15 07:29:01 +00006588 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006589 /// Sink a zext or sext into its user blocks if the target type doesn't
6590 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006591 if (TLI &&
6592 TLI->getTypeAction(CI->getContext(),
6593 TLI->getValueType(*DL, CI->getType())) ==
6594 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006595 return SinkCast(CI);
6596 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006597 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006598 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006599 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006600 }
Chris Lattneree588de2011-01-15 07:29:01 +00006601 return false;
6602 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006603
Chris Lattneree588de2011-01-15 07:29:01 +00006604 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006605 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006606 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006607
Chris Lattneree588de2011-01-15 07:29:01 +00006608 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006609 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006610 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006611 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006612 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006613 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6614 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006615 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006616 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006617 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006618
Chris Lattneree588de2011-01-15 07:29:01 +00006619 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006620 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6621 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006622 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006623 if (TLI) {
6624 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006625 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006626 SI->getOperand(0)->getType(), AS);
6627 }
Chris Lattneree588de2011-01-15 07:29:01 +00006628 return false;
6629 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006630
Matt Arsenault02d915b2017-03-15 22:35:20 +00006631 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6632 unsigned AS = RMW->getPointerAddressSpace();
6633 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6634 RMW->getType(), AS);
6635 }
6636
6637 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6638 unsigned AS = CmpX->getPointerAddressSpace();
6639 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6640 CmpX->getCompareOperand()->getType(), AS);
6641 }
6642
Yi Jiangd069f632014-04-21 19:34:27 +00006643 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6644
Geoff Berry5d534b62017-02-21 18:53:14 +00006645 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6646 EnableAndCmpSinking && TLI)
6647 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6648
Yi Jiangd069f632014-04-21 19:34:27 +00006649 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6650 BinOp->getOpcode() == Instruction::LShr)) {
6651 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6652 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006653 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006654
6655 return false;
6656 }
6657
Chris Lattneree588de2011-01-15 07:29:01 +00006658 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006659 if (GEPI->hasAllZeroIndices()) {
6660 /// The GEP operand must be a pointer, so must its result -> BitCast
6661 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6662 GEPI->getName(), GEPI);
6663 GEPI->replaceAllUsesWith(NC);
6664 GEPI->eraseFromParent();
6665 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006666 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006667 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006668 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006669 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6670 return true;
6671 }
Chris Lattneree588de2011-01-15 07:29:01 +00006672 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006673 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006674
Chris Lattneree588de2011-01-15 07:29:01 +00006675 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006676 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006677
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006678 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006679 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006680
Tim Northoveraeb8e062014-02-19 10:02:43 +00006681 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006682 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006683
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006684 if (auto *Switch = dyn_cast<SwitchInst>(I))
6685 return optimizeSwitchInst(Switch);
6686
Quentin Colombetc32615d2014-10-31 17:52:53 +00006687 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006688 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006689
Chris Lattneree588de2011-01-15 07:29:01 +00006690 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006691}
6692
James Molloyf01488e2016-01-15 09:20:19 +00006693/// Given an OR instruction, check to see if this is a bitreverse
6694/// idiom. If so, insert the new intrinsic and return true.
6695static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6696 const TargetLowering &TLI) {
6697 if (!I.getType()->isIntegerTy() ||
6698 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6699 TLI.getValueType(DL, I.getType(), true)))
6700 return false;
6701
6702 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006703 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006704 return false;
6705 Instruction *LastInst = Insts.back();
6706 I.replaceAllUsesWith(LastInst);
6707 RecursivelyDeleteTriviallyDeadInstructions(&I);
6708 return true;
6709}
6710
Chris Lattnerf2836d12007-03-31 04:06:36 +00006711// In this pass we look for GEP and cast instructions that are used
6712// across basic blocks and rewrite them to improve basic-block-at-a-time
6713// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006714bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006715 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006716 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006717
Chris Lattner7a277142011-01-15 07:14:54 +00006718 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006719 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006720 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006721 if (ModifiedDT)
6722 return true;
6723 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006724
James Molloyf01488e2016-01-15 09:20:19 +00006725 bool MadeBitReverse = true;
6726 while (TLI && MadeBitReverse) {
6727 MadeBitReverse = false;
6728 for (auto &I : reverse(BB)) {
6729 if (makeBitReverse(I, *DL, *TLI)) {
6730 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006731 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006732 break;
6733 }
6734 }
6735 }
James Molloy3ef84c42016-01-15 10:36:01 +00006736 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006737
Chris Lattnerf2836d12007-03-31 04:06:36 +00006738 return MadeChange;
6739}
Devang Patel53771ba2011-08-18 00:50:51 +00006740
6741// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006742// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006743// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006744bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006745 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006746 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006747 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006748 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006749 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006750 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006751 // Leave dbg.values that refer to an alloca alone. These
6752 // instrinsics describe the address of a variable (= the alloca)
6753 // being taken. They should not be moved next to the alloca
6754 // (and to the beginning of the scope), but rather stay close to
6755 // where said address is used.
6756 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006757 PrevNonDbgInst = Insn;
6758 continue;
6759 }
6760
6761 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6762 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006763 // If VI is a phi in a block with an EHPad terminator, we can't insert
6764 // after it.
6765 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6766 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00006767 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6768 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006769 if (isa<PHINode>(VI))
6770 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6771 else
6772 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006773 MadeChange = true;
6774 ++NumDbgValueMoved;
6775 }
6776 }
6777 }
6778 return MadeChange;
6779}
Tim Northovercea0abb2014-03-29 08:22:29 +00006780
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006781/// \brief Scale down both weights to fit into uint32_t.
6782static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6783 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006784 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006785 NewTrue = NewTrue / Scale;
6786 NewFalse = NewFalse / Scale;
6787}
6788
6789/// \brief Some targets prefer to split a conditional branch like:
6790/// \code
6791/// %0 = icmp ne i32 %a, 0
6792/// %1 = icmp ne i32 %b, 0
6793/// %or.cond = or i1 %0, %1
6794/// br i1 %or.cond, label %TrueBB, label %FalseBB
6795/// \endcode
6796/// into multiple branch instructions like:
6797/// \code
6798/// bb1:
6799/// %0 = icmp ne i32 %a, 0
6800/// br i1 %0, label %TrueBB, label %bb2
6801/// bb2:
6802/// %1 = icmp ne i32 %b, 0
6803/// br i1 %1, label %TrueBB, label %FalseBB
6804/// \endcode
6805/// This usually allows instruction selection to do even further optimizations
6806/// and combine the compare with the branch instruction. Currently this is
6807/// applied for targets which have "cheap" jump instructions.
6808///
6809/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6810///
6811bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006812 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006813 return false;
6814
6815 bool MadeChange = false;
6816 for (auto &BB : F) {
6817 // Does this BB end with the following?
6818 // %cond1 = icmp|fcmp|binary instruction ...
6819 // %cond2 = icmp|fcmp|binary instruction ...
6820 // %cond.or = or|and i1 %cond1, cond2
6821 // br i1 %cond.or label %dest1, label %dest2"
6822 BinaryOperator *LogicOp;
6823 BasicBlock *TBB, *FBB;
6824 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6825 continue;
6826
Sanjay Patel42574202015-09-02 19:23:23 +00006827 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6828 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6829 continue;
6830
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006831 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006832 Value *Cond1, *Cond2;
6833 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6834 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006835 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006836 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6837 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006838 Opc = Instruction::Or;
6839 else
6840 continue;
6841
6842 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6843 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6844 continue;
6845
6846 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6847
6848 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006849 auto TmpBB =
6850 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6851 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006852
6853 // Update original basic block by using the first condition directly by the
6854 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006855 Br1->setCondition(Cond1);
6856 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006857
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006858 // Depending on the conditon we have to either replace the true or the false
6859 // successor of the original branch instruction.
6860 if (Opc == Instruction::And)
6861 Br1->setSuccessor(0, TmpBB);
6862 else
6863 Br1->setSuccessor(1, TmpBB);
6864
6865 // Fill in the new basic block.
6866 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006867 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6868 I->removeFromParent();
6869 I->insertBefore(Br2);
6870 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006871
6872 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006873 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006874 // the newly generated BB (NewBB). In the other successor we need to add one
6875 // incoming edge to the PHI nodes, because both branch instructions target
6876 // now the same successor. Depending on the original branch condition
6877 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006878 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006879 // This doesn't change the successor order of the just created branch
6880 // instruction (or any other instruction).
6881 if (Opc == Instruction::Or)
6882 std::swap(TBB, FBB);
6883
6884 // Replace the old BB with the new BB.
6885 for (auto &I : *TBB) {
6886 PHINode *PN = dyn_cast<PHINode>(&I);
6887 if (!PN)
6888 break;
6889 int i;
6890 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6891 PN->setIncomingBlock(i, TmpBB);
6892 }
6893
6894 // Add another incoming edge form the new BB.
6895 for (auto &I : *FBB) {
6896 PHINode *PN = dyn_cast<PHINode>(&I);
6897 if (!PN)
6898 break;
6899 auto *Val = PN->getIncomingValueForBlock(&BB);
6900 PN->addIncoming(Val, TmpBB);
6901 }
6902
6903 // Update the branch weights (from SelectionDAGBuilder::
6904 // FindMergedConditions).
6905 if (Opc == Instruction::Or) {
6906 // Codegen X | Y as:
6907 // BB1:
6908 // jmp_if_X TBB
6909 // jmp TmpBB
6910 // TmpBB:
6911 // jmp_if_Y TBB
6912 // jmp FBB
6913 //
6914
6915 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6916 // The requirement is that
6917 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6918 // = TrueProb for orignal BB.
6919 // Assuming the orignal weights are A and B, one choice is to set BB1's
6920 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6921 // assumes that
6922 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6923 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6924 // TmpBB, but the math is more complicated.
6925 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006926 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006927 uint64_t NewTrueWeight = TrueWeight;
6928 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6929 scaleWeights(NewTrueWeight, NewFalseWeight);
6930 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6931 .createBranchWeights(TrueWeight, FalseWeight));
6932
6933 NewTrueWeight = TrueWeight;
6934 NewFalseWeight = 2 * FalseWeight;
6935 scaleWeights(NewTrueWeight, NewFalseWeight);
6936 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6937 .createBranchWeights(TrueWeight, FalseWeight));
6938 }
6939 } else {
6940 // Codegen X & Y as:
6941 // BB1:
6942 // jmp_if_X TmpBB
6943 // jmp FBB
6944 // TmpBB:
6945 // jmp_if_Y TBB
6946 // jmp FBB
6947 //
6948 // This requires creation of TmpBB after CurBB.
6949
6950 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6951 // The requirement is that
6952 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6953 // = FalseProb for orignal BB.
6954 // Assuming the orignal weights are A and B, one choice is to set BB1's
6955 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6956 // assumes that
6957 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6958 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006959 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006960 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6961 uint64_t NewFalseWeight = FalseWeight;
6962 scaleWeights(NewTrueWeight, NewFalseWeight);
6963 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6964 .createBranchWeights(TrueWeight, FalseWeight));
6965
6966 NewTrueWeight = 2 * TrueWeight;
6967 NewFalseWeight = FalseWeight;
6968 scaleWeights(NewTrueWeight, NewFalseWeight);
6969 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6970 .createBranchWeights(TrueWeight, FalseWeight));
6971 }
6972 }
6973
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006974 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006975 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006976 ModifiedDT = true;
6977
6978 MadeChange = true;
6979
6980 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6981 TmpBB->dump());
6982 }
6983 return MadeChange;
6984}