1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/MDBuilder.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/ValueHandle.h"
36 #include "llvm/IR/ValueMap.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/BuildLibCalls.h"
46 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
49 using namespace llvm;
50 using namespace llvm::PatternMatch;
51
52 #define DEBUG_TYPE "codegenprepare"
53
54 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
55 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
56 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
57 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
58 "sunken Cmps");
59 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
60 "of sunken Casts");
61 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
62 "computations were sunk");
63 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
64 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
65 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
66 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
67 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
68 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
69 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
70
71 static cl::opt<bool> DisableBranchOpts(
72 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
73 cl::desc("Disable branch optimizations in CodeGenPrepare"));
74
75 static cl::opt<bool> DisableSelectToBranch(
76 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
77 cl::desc("Disable select to branch conversion."));
78
79 static cl::opt<bool> AddrSinkUsingGEPs(
80 "addr-sink-using-gep", cl::Hidden, cl::init(false),
81 cl::desc("Address sinking in CGP using GEPs."));
82
83 static cl::opt<bool> EnableAndCmpSinking(
84 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
85 cl::desc("Enable sinkinig and/cmp into branches."));
86
87 static cl::opt<bool> DisableStoreExtract(
88 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
89 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
90
91 static cl::opt<bool> StressStoreExtract(
92 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
93 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
94
95 static cl::opt<bool> DisableExtLdPromotion(
96 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
97 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
98 "CodeGenPrepare"));
99
100 static cl::opt<bool> StressExtLdPromotion(
101 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
103 "optimization in CodeGenPrepare"));
104
105 namespace {
106 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
107 struct TypeIsSExt {
108 Type *Ty;
109 bool IsSExt;
TypeIsSExt__anon8f33d8c30111::TypeIsSExt110 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
111 };
112 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
113 class TypePromotionTransaction;
114
115 class CodeGenPrepare : public FunctionPass {
116 /// TLI - Keep a pointer of a TargetLowering to consult for determining
117 /// transformation profitability.
118 const TargetMachine *TM;
119 const TargetLowering *TLI;
120 const TargetTransformInfo *TTI;
121 const TargetLibraryInfo *TLInfo;
122 DominatorTree *DT;
123
124 /// CurInstIterator - As we scan instructions optimizing them, this is the
125 /// next instruction to optimize. Xforms that can invalidate this should
126 /// update it.
127 BasicBlock::iterator CurInstIterator;
128
129 /// Keeps track of non-local addresses that have been sunk into a block.
130 /// This allows us to avoid inserting duplicate code for blocks with
131 /// multiple load/stores of the same address.
132 ValueMap<Value*, Value*> SunkAddrs;
133
134 /// Keeps track of all truncates inserted for the current function.
135 SetOfInstrs InsertedTruncsSet;
136 /// Keeps track of the type of the related instruction before their
137 /// promotion for the current function.
138 InstrToOrigTy PromotedInsts;
139
140 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
141 /// be updated.
142 bool ModifiedDT;
143
144 /// OptSize - True if optimizing for size.
145 bool OptSize;
146
147 public:
148 static char ID; // Pass identification, replacement for typeid
CodeGenPrepare(const TargetMachine * TM=nullptr)149 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
150 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
151 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
152 }
153 bool runOnFunction(Function &F) override;
154
getPassName() const155 const char *getPassName() const override { return "CodeGen Prepare"; }
156
getAnalysisUsage(AnalysisUsage & AU) const157 void getAnalysisUsage(AnalysisUsage &AU) const override {
158 AU.addPreserved<DominatorTreeWrapperPass>();
159 AU.addRequired<TargetLibraryInfo>();
160 AU.addRequired<TargetTransformInfo>();
161 }
162
163 private:
164 bool EliminateFallThrough(Function &F);
165 bool EliminateMostlyEmptyBlocks(Function &F);
166 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
167 void EliminateMostlyEmptyBlock(BasicBlock *BB);
168 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
169 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
170 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
171 bool OptimizeInlineAsmInst(CallInst *CS);
172 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
173 bool MoveExtToFormExtLoad(Instruction *&I);
174 bool OptimizeExtUses(Instruction *I);
175 bool OptimizeSelectInst(SelectInst *SI);
176 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
177 bool OptimizeExtractElementInst(Instruction *Inst);
178 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
179 bool PlaceDbgValues(Function &F);
180 bool sinkAndCmp(Function &F);
181 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
182 Instruction *&Inst,
183 const SmallVectorImpl<Instruction *> &Exts,
184 unsigned CreatedInst);
185 bool splitBranchCondition(Function &F);
186 };
187 }
188
189 char CodeGenPrepare::ID = 0;
190 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
191 "Optimize for code generation", false, false)
192
createCodeGenPreparePass(const TargetMachine * TM)193 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
194 return new CodeGenPrepare(TM);
195 }
196
runOnFunction(Function & F)197 bool CodeGenPrepare::runOnFunction(Function &F) {
198 if (skipOptnoneFunction(F))
199 return false;
200
201 bool EverMadeChange = false;
202 // Clear per function information.
203 InsertedTruncsSet.clear();
204 PromotedInsts.clear();
205
206 ModifiedDT = false;
207 if (TM)
208 TLI = TM->getSubtargetImpl()->getTargetLowering();
209 TLInfo = &getAnalysis<TargetLibraryInfo>();
210 TTI = &getAnalysis<TargetTransformInfo>();
211 DominatorTreeWrapperPass *DTWP =
212 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
213 DT = DTWP ? &DTWP->getDomTree() : nullptr;
214 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
215 Attribute::OptimizeForSize);
216
217 /// This optimization identifies DIV instructions that can be
218 /// profitably bypassed and carried out with a shorter, faster divide.
219 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
220 const DenseMap<unsigned int, unsigned int> &BypassWidths =
221 TLI->getBypassSlowDivWidths();
222 for (Function::iterator I = F.begin(); I != F.end(); I++)
223 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
224 }
225
226 // Eliminate blocks that contain only PHI nodes and an
227 // unconditional branch.
228 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
229
230 // llvm.dbg.value is far away from the value then iSel may not be able
231 // handle it properly. iSel will drop llvm.dbg.value if it can not
232 // find a node corresponding to the value.
233 EverMadeChange |= PlaceDbgValues(F);
234
235 // If there is a mask, compare against zero, and branch that can be combined
236 // into a single target instruction, push the mask and compare into branch
237 // users. Do this before OptimizeBlock -> OptimizeInst ->
238 // OptimizeCmpExpression, which perturbs the pattern being searched for.
239 if (!DisableBranchOpts) {
240 EverMadeChange |= sinkAndCmp(F);
241 EverMadeChange |= splitBranchCondition(F);
242 }
243
244 bool MadeChange = true;
245 while (MadeChange) {
246 MadeChange = false;
247 for (Function::iterator I = F.begin(); I != F.end(); ) {
248 BasicBlock *BB = I++;
249 bool ModifiedDTOnIteration = false;
250 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
251
252 // Restart BB iteration if the dominator tree of the Function was changed
253 ModifiedDT |= ModifiedDTOnIteration;
254 if (ModifiedDTOnIteration)
255 break;
256 }
257 EverMadeChange |= MadeChange;
258 }
259
260 SunkAddrs.clear();
261
262 if (!DisableBranchOpts) {
263 MadeChange = false;
264 SmallPtrSet<BasicBlock*, 8> WorkList;
265 for (BasicBlock &BB : F) {
266 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
267 MadeChange |= ConstantFoldTerminator(&BB, true);
268 if (!MadeChange) continue;
269
270 for (SmallVectorImpl<BasicBlock*>::iterator
271 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
272 if (pred_begin(*II) == pred_end(*II))
273 WorkList.insert(*II);
274 }
275
276 // Delete the dead blocks and any of their dead successors.
277 MadeChange |= !WorkList.empty();
278 while (!WorkList.empty()) {
279 BasicBlock *BB = *WorkList.begin();
280 WorkList.erase(BB);
281 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
282
283 DeleteDeadBlock(BB);
284
285 for (SmallVectorImpl<BasicBlock*>::iterator
286 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
287 if (pred_begin(*II) == pred_end(*II))
288 WorkList.insert(*II);
289 }
290
291 // Merge pairs of basic blocks with unconditional branches, connected by
292 // a single edge.
293 if (EverMadeChange || MadeChange)
294 MadeChange |= EliminateFallThrough(F);
295
296 if (MadeChange)
297 ModifiedDT = true;
298 EverMadeChange |= MadeChange;
299 }
300
301 if (ModifiedDT && DT)
302 DT->recalculate(F);
303
304 return EverMadeChange;
305 }
306
307 /// EliminateFallThrough - Merge basic blocks which are connected
308 /// by a single edge, where one of the basic blocks has a single successor
309 /// pointing to the other basic block, which has a single predecessor.
EliminateFallThrough(Function & F)310 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
311 bool Changed = false;
312 // Scan all of the blocks in the function, except for the entry block.
313 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
314 BasicBlock *BB = I++;
315 // If the destination block has a single pred, then this is a trivial
316 // edge, just collapse it.
317 BasicBlock *SinglePred = BB->getSinglePredecessor();
318
319 // Don't merge if BB's address is taken.
320 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
321
322 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
323 if (Term && !Term->isConditional()) {
324 Changed = true;
325 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
326 // Remember if SinglePred was the entry block of the function.
327 // If so, we will need to move BB back to the entry position.
328 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
329 MergeBasicBlockIntoOnlyPred(BB, this);
330
331 if (isEntry && BB != &BB->getParent()->getEntryBlock())
332 BB->moveBefore(&BB->getParent()->getEntryBlock());
333
334 // We have erased a block. Update the iterator.
335 I = BB;
336 }
337 }
338 return Changed;
339 }
340
341 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
342 /// debug info directives, and an unconditional branch. Passes before isel
343 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
344 /// isel. Start by eliminating these blocks so we can split them the way we
345 /// want them.
EliminateMostlyEmptyBlocks(Function & F)346 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
347 bool MadeChange = false;
348 // Note that this intentionally skips the entry block.
349 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
350 BasicBlock *BB = I++;
351
352 // If this block doesn't end with an uncond branch, ignore it.
353 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
354 if (!BI || !BI->isUnconditional())
355 continue;
356
357 // If the instruction before the branch (skipping debug info) isn't a phi
358 // node, then other stuff is happening here.
359 BasicBlock::iterator BBI = BI;
360 if (BBI != BB->begin()) {
361 --BBI;
362 while (isa<DbgInfoIntrinsic>(BBI)) {
363 if (BBI == BB->begin())
364 break;
365 --BBI;
366 }
367 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
368 continue;
369 }
370
371 // Do not break infinite loops.
372 BasicBlock *DestBB = BI->getSuccessor(0);
373 if (DestBB == BB)
374 continue;
375
376 if (!CanMergeBlocks(BB, DestBB))
377 continue;
378
379 EliminateMostlyEmptyBlock(BB);
380 MadeChange = true;
381 }
382 return MadeChange;
383 }
384
385 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
386 /// single uncond branch between them, and BB contains no other non-phi
387 /// instructions.
CanMergeBlocks(const BasicBlock * BB,const BasicBlock * DestBB) const388 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
389 const BasicBlock *DestBB) const {
390 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
391 // the successor. If there are more complex condition (e.g. preheaders),
392 // don't mess around with them.
393 BasicBlock::const_iterator BBI = BB->begin();
394 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
395 for (const User *U : PN->users()) {
396 const Instruction *UI = cast<Instruction>(U);
397 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
398 return false;
399 // If User is inside DestBB block and it is a PHINode then check
400 // incoming value. If incoming value is not from BB then this is
401 // a complex condition (e.g. preheaders) we want to avoid here.
402 if (UI->getParent() == DestBB) {
403 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
404 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
405 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
406 if (Insn && Insn->getParent() == BB &&
407 Insn->getParent() != UPN->getIncomingBlock(I))
408 return false;
409 }
410 }
411 }
412 }
413
414 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
415 // and DestBB may have conflicting incoming values for the block. If so, we
416 // can't merge the block.
417 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
418 if (!DestBBPN) return true; // no conflict.
419
420 // Collect the preds of BB.
421 SmallPtrSet<const BasicBlock*, 16> BBPreds;
422 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
423 // It is faster to get preds from a PHI than with pred_iterator.
424 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
425 BBPreds.insert(BBPN->getIncomingBlock(i));
426 } else {
427 BBPreds.insert(pred_begin(BB), pred_end(BB));
428 }
429
430 // Walk the preds of DestBB.
431 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
432 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
433 if (BBPreds.count(Pred)) { // Common predecessor?
434 BBI = DestBB->begin();
435 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
436 const Value *V1 = PN->getIncomingValueForBlock(Pred);
437 const Value *V2 = PN->getIncomingValueForBlock(BB);
438
439 // If V2 is a phi node in BB, look up what the mapped value will be.
440 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
441 if (V2PN->getParent() == BB)
442 V2 = V2PN->getIncomingValueForBlock(Pred);
443
444 // If there is a conflict, bail out.
445 if (V1 != V2) return false;
446 }
447 }
448 }
449
450 return true;
451 }
452
453
454 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
455 /// an unconditional branch in it.
EliminateMostlyEmptyBlock(BasicBlock * BB)456 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
457 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
458 BasicBlock *DestBB = BI->getSuccessor(0);
459
460 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
461
462 // If the destination block has a single pred, then this is a trivial edge,
463 // just collapse it.
464 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
465 if (SinglePred != DestBB) {
466 // Remember if SinglePred was the entry block of the function. If so, we
467 // will need to move BB back to the entry position.
468 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
469 MergeBasicBlockIntoOnlyPred(DestBB, this);
470
471 if (isEntry && BB != &BB->getParent()->getEntryBlock())
472 BB->moveBefore(&BB->getParent()->getEntryBlock());
473
474 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
475 return;
476 }
477 }
478
479 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
480 // to handle the new incoming edges it is about to have.
481 PHINode *PN;
482 for (BasicBlock::iterator BBI = DestBB->begin();
483 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
484 // Remove the incoming value for BB, and remember it.
485 Value *InVal = PN->removeIncomingValue(BB, false);
486
487 // Two options: either the InVal is a phi node defined in BB or it is some
488 // value that dominates BB.
489 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
490 if (InValPhi && InValPhi->getParent() == BB) {
491 // Add all of the input values of the input PHI as inputs of this phi.
492 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
493 PN->addIncoming(InValPhi->getIncomingValue(i),
494 InValPhi->getIncomingBlock(i));
495 } else {
496 // Otherwise, add one instance of the dominating value for each edge that
497 // we will be adding.
498 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
499 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
500 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
501 } else {
502 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
503 PN->addIncoming(InVal, *PI);
504 }
505 }
506 }
507
508 // The PHIs are now updated, change everything that refers to BB to use
509 // DestBB and remove BB.
510 BB->replaceAllUsesWith(DestBB);
511 if (DT && !ModifiedDT) {
512 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
513 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
514 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
515 DT->changeImmediateDominator(DestBB, NewIDom);
516 DT->eraseNode(BB);
517 }
518 BB->eraseFromParent();
519 ++NumBlocksElim;
520
521 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
522 }
523
524 /// SinkCast - Sink the specified cast instruction into its user blocks
SinkCast(CastInst * CI)525 static bool SinkCast(CastInst *CI) {
526 BasicBlock *DefBB = CI->getParent();
527
528 /// InsertedCasts - Only insert a cast in each block once.
529 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
530
531 bool MadeChange = false;
532 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
533 UI != E; ) {
534 Use &TheUse = UI.getUse();
535 Instruction *User = cast<Instruction>(*UI);
536
537 // Figure out which BB this cast is used in. For PHI's this is the
538 // appropriate predecessor block.
539 BasicBlock *UserBB = User->getParent();
540 if (PHINode *PN = dyn_cast<PHINode>(User)) {
541 UserBB = PN->getIncomingBlock(TheUse);
542 }
543
544 // Preincrement use iterator so we don't invalidate it.
545 ++UI;
546
547 // If this user is in the same block as the cast, don't change the cast.
548 if (UserBB == DefBB) continue;
549
550 // If we have already inserted a cast into this block, use it.
551 CastInst *&InsertedCast = InsertedCasts[UserBB];
552
553 if (!InsertedCast) {
554 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
555 InsertedCast =
556 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
557 InsertPt);
558 MadeChange = true;
559 }
560
561 // Replace a use of the cast with a use of the new cast.
562 TheUse = InsertedCast;
563 ++NumCastUses;
564 }
565
566 // If we removed all uses, nuke the cast.
567 if (CI->use_empty()) {
568 CI->eraseFromParent();
569 MadeChange = true;
570 }
571
572 return MadeChange;
573 }
574
575 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
576 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
577 /// sink it into user blocks to reduce the number of virtual
578 /// registers that must be created and coalesced.
579 ///
580 /// Return true if any changes are made.
581 ///
OptimizeNoopCopyExpression(CastInst * CI,const TargetLowering & TLI)582 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
583 // If this is a noop copy,
584 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
585 EVT DstVT = TLI.getValueType(CI->getType());
586
587 // This is an fp<->int conversion?
588 if (SrcVT.isInteger() != DstVT.isInteger())
589 return false;
590
591 // If this is an extension, it will be a zero or sign extension, which
592 // isn't a noop.
593 if (SrcVT.bitsLT(DstVT)) return false;
594
595 // If these values will be promoted, find out what they will be promoted
596 // to. This helps us consider truncates on PPC as noop copies when they
597 // are.
598 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
599 TargetLowering::TypePromoteInteger)
600 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
601 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
602 TargetLowering::TypePromoteInteger)
603 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
604
605 // If, after promotion, these are the same types, this is a noop copy.
606 if (SrcVT != DstVT)
607 return false;
608
609 return SinkCast(CI);
610 }
611
612 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
613 /// the number of virtual registers that must be created and coalesced. This is
614 /// a clear win except on targets with multiple condition code registers
615 /// (PowerPC), where it might lose; some adjustment may be wanted there.
616 ///
617 /// Return true if any changes are made.
OptimizeCmpExpression(CmpInst * CI)618 static bool OptimizeCmpExpression(CmpInst *CI) {
619 BasicBlock *DefBB = CI->getParent();
620
621 /// InsertedCmp - Only insert a cmp in each block once.
622 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
623
624 bool MadeChange = false;
625 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
626 UI != E; ) {
627 Use &TheUse = UI.getUse();
628 Instruction *User = cast<Instruction>(*UI);
629
630 // Preincrement use iterator so we don't invalidate it.
631 ++UI;
632
633 // Don't bother for PHI nodes.
634 if (isa<PHINode>(User))
635 continue;
636
637 // Figure out which BB this cmp is used in.
638 BasicBlock *UserBB = User->getParent();
639
640 // If this user is in the same block as the cmp, don't change the cmp.
641 if (UserBB == DefBB) continue;
642
643 // If we have already inserted a cmp into this block, use it.
644 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
645
646 if (!InsertedCmp) {
647 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
648 InsertedCmp =
649 CmpInst::Create(CI->getOpcode(),
650 CI->getPredicate(), CI->getOperand(0),
651 CI->getOperand(1), "", InsertPt);
652 MadeChange = true;
653 }
654
655 // Replace a use of the cmp with a use of the new cmp.
656 TheUse = InsertedCmp;
657 ++NumCmpUses;
658 }
659
660 // If we removed all uses, nuke the cmp.
661 if (CI->use_empty())
662 CI->eraseFromParent();
663
664 return MadeChange;
665 }
666
667 /// isExtractBitsCandidateUse - Check if the candidates could
668 /// be combined with shift instruction, which includes:
669 /// 1. Truncate instruction
670 /// 2. And instruction and the imm is a mask of the low bits:
671 /// imm & (imm+1) == 0
isExtractBitsCandidateUse(Instruction * User)672 static bool isExtractBitsCandidateUse(Instruction *User) {
673 if (!isa<TruncInst>(User)) {
674 if (User->getOpcode() != Instruction::And ||
675 !isa<ConstantInt>(User->getOperand(1)))
676 return false;
677
678 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
679
680 if ((Cimm & (Cimm + 1)).getBoolValue())
681 return false;
682 }
683 return true;
684 }
685
686 /// SinkShiftAndTruncate - sink both shift and truncate instruction
687 /// to the use of truncate's BB.
688 static bool
SinkShiftAndTruncate(BinaryOperator * ShiftI,Instruction * User,ConstantInt * CI,DenseMap<BasicBlock *,BinaryOperator * > & InsertedShifts,const TargetLowering & TLI)689 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
690 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
691 const TargetLowering &TLI) {
692 BasicBlock *UserBB = User->getParent();
693 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
694 TruncInst *TruncI = dyn_cast<TruncInst>(User);
695 bool MadeChange = false;
696
697 for (Value::user_iterator TruncUI = TruncI->user_begin(),
698 TruncE = TruncI->user_end();
699 TruncUI != TruncE;) {
700
701 Use &TruncTheUse = TruncUI.getUse();
702 Instruction *TruncUser = cast<Instruction>(*TruncUI);
703 // Preincrement use iterator so we don't invalidate it.
704
705 ++TruncUI;
706
707 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
708 if (!ISDOpcode)
709 continue;
710
711 // If the use is actually a legal node, there will not be an
712 // implicit truncate.
713 // FIXME: always querying the result type is just an
714 // approximation; some nodes' legality is determined by the
715 // operand or other means. There's no good way to find out though.
716 if (TLI.isOperationLegalOrCustom(
717 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
718 continue;
719
720 // Don't bother for PHI nodes.
721 if (isa<PHINode>(TruncUser))
722 continue;
723
724 BasicBlock *TruncUserBB = TruncUser->getParent();
725
726 if (UserBB == TruncUserBB)
727 continue;
728
729 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
730 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
731
732 if (!InsertedShift && !InsertedTrunc) {
733 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
734 // Sink the shift
735 if (ShiftI->getOpcode() == Instruction::AShr)
736 InsertedShift =
737 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
738 else
739 InsertedShift =
740 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
741
742 // Sink the trunc
743 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
744 TruncInsertPt++;
745
746 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
747 TruncI->getType(), "", TruncInsertPt);
748
749 MadeChange = true;
750
751 TruncTheUse = InsertedTrunc;
752 }
753 }
754 return MadeChange;
755 }
756
757 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
758 /// the uses could potentially be combined with this shift instruction and
759 /// generate BitExtract instruction. It will only be applied if the architecture
760 /// supports BitExtract instruction. Here is an example:
761 /// BB1:
762 /// %x.extract.shift = lshr i64 %arg1, 32
763 /// BB2:
764 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
765 /// ==>
766 ///
767 /// BB2:
768 /// %x.extract.shift.1 = lshr i64 %arg1, 32
769 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
770 ///
771 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
772 /// instruction.
773 /// Return true if any changes are made.
OptimizeExtractBits(BinaryOperator * ShiftI,ConstantInt * CI,const TargetLowering & TLI)774 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
775 const TargetLowering &TLI) {
776 BasicBlock *DefBB = ShiftI->getParent();
777
778 /// Only insert instructions in each block once.
779 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
780
781 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
782
783 bool MadeChange = false;
784 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
785 UI != E;) {
786 Use &TheUse = UI.getUse();
787 Instruction *User = cast<Instruction>(*UI);
788 // Preincrement use iterator so we don't invalidate it.
789 ++UI;
790
791 // Don't bother for PHI nodes.
792 if (isa<PHINode>(User))
793 continue;
794
795 if (!isExtractBitsCandidateUse(User))
796 continue;
797
798 BasicBlock *UserBB = User->getParent();
799
800 if (UserBB == DefBB) {
801 // If the shift and truncate instruction are in the same BB. The use of
802 // the truncate(TruncUse) may still introduce another truncate if not
803 // legal. In this case, we would like to sink both shift and truncate
804 // instruction to the BB of TruncUse.
805 // for example:
806 // BB1:
807 // i64 shift.result = lshr i64 opnd, imm
808 // trunc.result = trunc shift.result to i16
809 //
810 // BB2:
811 // ----> We will have an implicit truncate here if the architecture does
812 // not have i16 compare.
813 // cmp i16 trunc.result, opnd2
814 //
815 if (isa<TruncInst>(User) && shiftIsLegal
816 // If the type of the truncate is legal, no trucate will be
817 // introduced in other basic blocks.
818 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
819 MadeChange =
820 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
821
822 continue;
823 }
824 // If we have already inserted a shift into this block, use it.
825 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
826
827 if (!InsertedShift) {
828 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
829
830 if (ShiftI->getOpcode() == Instruction::AShr)
831 InsertedShift =
832 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
833 else
834 InsertedShift =
835 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
836
837 MadeChange = true;
838 }
839
840 // Replace a use of the shift with a use of the new shift.
841 TheUse = InsertedShift;
842 }
843
844 // If we removed all uses, nuke the shift.
845 if (ShiftI->use_empty())
846 ShiftI->eraseFromParent();
847
848 return MadeChange;
849 }
850
851 // ScalarizeMaskedLoad() translates masked load intrinsic, like
852 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
853 // <16 x i1> %mask, <16 x i32> %passthru)
854 // to a chain of basic blocks, whith loading element one-by-one if
855 // the appropriate mask bit is set
856 //
857 // %1 = bitcast i8* %addr to i32*
858 // %2 = extractelement <16 x i1> %mask, i32 0
859 // %3 = icmp eq i1 %2, true
860 // br i1 %3, label %cond.load, label %else
861 //
862 //cond.load: ; preds = %0
863 // %4 = getelementptr i32* %1, i32 0
864 // %5 = load i32* %4
865 // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
866 // br label %else
867 //
868 //else: ; preds = %0, %cond.load
869 // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
870 // %7 = extractelement <16 x i1> %mask, i32 1
871 // %8 = icmp eq i1 %7, true
872 // br i1 %8, label %cond.load1, label %else2
873 //
874 //cond.load1: ; preds = %else
875 // %9 = getelementptr i32* %1, i32 1
876 // %10 = load i32* %9
877 // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
878 // br label %else2
879 //
880 //else2: ; preds = %else, %cond.load1
881 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
882 // %12 = extractelement <16 x i1> %mask, i32 2
883 // %13 = icmp eq i1 %12, true
884 // br i1 %13, label %cond.load4, label %else5
885 //
ScalarizeMaskedLoad(CallInst * CI)886 static void ScalarizeMaskedLoad(CallInst *CI) {
887 Value *Ptr = CI->getArgOperand(0);
888 Value *Src0 = CI->getArgOperand(3);
889 Value *Mask = CI->getArgOperand(2);
890 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
891 Type *EltTy = VecType->getElementType();
892
893 assert(VecType && "Unexpected return type of masked load intrinsic");
894
895 IRBuilder<> Builder(CI->getContext());
896 Instruction *InsertPt = CI;
897 BasicBlock *IfBlock = CI->getParent();
898 BasicBlock *CondBlock = nullptr;
899 BasicBlock *PrevIfBlock = CI->getParent();
900 Builder.SetInsertPoint(InsertPt);
901
902 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
903
904 // Bitcast %addr fron i8* to EltTy*
905 Type *NewPtrType =
906 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
907 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
908 Value *UndefVal = UndefValue::get(VecType);
909
910 // The result vector
911 Value *VResult = UndefVal;
912
913 PHINode *Phi = nullptr;
914 Value *PrevPhi = UndefVal;
915
916 unsigned VectorWidth = VecType->getNumElements();
917 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
918
919 // Fill the "else" block, created in the previous iteration
920 //
921 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
922 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
923 // %to_load = icmp eq i1 %mask_1, true
924 // br i1 %to_load, label %cond.load, label %else
925 //
926 if (Idx > 0) {
927 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
928 Phi->addIncoming(VResult, CondBlock);
929 Phi->addIncoming(PrevPhi, PrevIfBlock);
930 PrevPhi = Phi;
931 VResult = Phi;
932 }
933
934 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
935 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
936 ConstantInt::get(Predicate->getType(), 1));
937
938 // Create "cond" block
939 //
940 // %EltAddr = getelementptr i32* %1, i32 0
941 // %Elt = load i32* %EltAddr
942 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
943 //
944 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
945 Builder.SetInsertPoint(InsertPt);
946
947 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
948 LoadInst* Load = Builder.CreateLoad(Gep, false);
949 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
950
951 // Create "else" block, fill it in the next iteration
952 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
953 Builder.SetInsertPoint(InsertPt);
954 Instruction *OldBr = IfBlock->getTerminator();
955 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
956 OldBr->eraseFromParent();
957 PrevIfBlock = IfBlock;
958 IfBlock = NewIfBlock;
959 }
960
961 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
962 Phi->addIncoming(VResult, CondBlock);
963 Phi->addIncoming(PrevPhi, PrevIfBlock);
964 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
965 CI->replaceAllUsesWith(NewI);
966 CI->eraseFromParent();
967 }
968
969 // ScalarizeMaskedStore() translates masked store intrinsic, like
970 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
971 // <16 x i1> %mask)
972 // to a chain of basic blocks, that stores element one-by-one if
973 // the appropriate mask bit is set
974 //
975 // %1 = bitcast i8* %addr to i32*
976 // %2 = extractelement <16 x i1> %mask, i32 0
977 // %3 = icmp eq i1 %2, true
978 // br i1 %3, label %cond.store, label %else
979 //
980 // cond.store: ; preds = %0
981 // %4 = extractelement <16 x i32> %val, i32 0
982 // %5 = getelementptr i32* %1, i32 0
983 // store i32 %4, i32* %5
984 // br label %else
985 //
986 // else: ; preds = %0, %cond.store
987 // %6 = extractelement <16 x i1> %mask, i32 1
988 // %7 = icmp eq i1 %6, true
989 // br i1 %7, label %cond.store1, label %else2
990 //
991 // cond.store1: ; preds = %else
992 // %8 = extractelement <16 x i32> %val, i32 1
993 // %9 = getelementptr i32* %1, i32 1
994 // store i32 %8, i32* %9
995 // br label %else2
996 // . . .
ScalarizeMaskedStore(CallInst * CI)997 static void ScalarizeMaskedStore(CallInst *CI) {
998 Value *Ptr = CI->getArgOperand(1);
999 Value *Src = CI->getArgOperand(0);
1000 Value *Mask = CI->getArgOperand(3);
1001
1002 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1003 Type *EltTy = VecType->getElementType();
1004
1005 assert(VecType && "Unexpected data type in masked store intrinsic");
1006
1007 IRBuilder<> Builder(CI->getContext());
1008 Instruction *InsertPt = CI;
1009 BasicBlock *IfBlock = CI->getParent();
1010 Builder.SetInsertPoint(InsertPt);
1011 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1012
1013 // Bitcast %addr fron i8* to EltTy*
1014 Type *NewPtrType =
1015 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1016 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1017
1018 unsigned VectorWidth = VecType->getNumElements();
1019 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1020
1021 // Fill the "else" block, created in the previous iteration
1022 //
1023 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1024 // %to_store = icmp eq i1 %mask_1, true
1025 // br i1 %to_load, label %cond.store, label %else
1026 //
1027 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1028 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1029 ConstantInt::get(Predicate->getType(), 1));
1030
1031 // Create "cond" block
1032 //
1033 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1034 // %EltAddr = getelementptr i32* %1, i32 0
1035 // %store i32 %OneElt, i32* %EltAddr
1036 //
1037 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1038 Builder.SetInsertPoint(InsertPt);
1039
1040 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1041 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1042 Builder.CreateStore(OneElt, Gep);
1043
1044 // Create "else" block, fill it in the next iteration
1045 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1046 Builder.SetInsertPoint(InsertPt);
1047 Instruction *OldBr = IfBlock->getTerminator();
1048 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1049 OldBr->eraseFromParent();
1050 IfBlock = NewIfBlock;
1051 }
1052 CI->eraseFromParent();
1053 }
1054
OptimizeCallInst(CallInst * CI,bool & ModifiedDT)1055 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
1056 BasicBlock *BB = CI->getParent();
1057
1058 // Lower inline assembly if we can.
1059 // If we found an inline asm expession, and if the target knows how to
1060 // lower it to normal LLVM code, do so now.
1061 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1062 if (TLI->ExpandInlineAsm(CI)) {
1063 // Avoid invalidating the iterator.
1064 CurInstIterator = BB->begin();
1065 // Avoid processing instructions out of order, which could cause
1066 // reuse before a value is defined.
1067 SunkAddrs.clear();
1068 return true;
1069 }
1070 // Sink address computing for memory operands into the block.
1071 if (OptimizeInlineAsmInst(CI))
1072 return true;
1073 }
1074
1075 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
1076 if (II) {
1077 switch (II->getIntrinsicID()) {
1078 default: break;
1079 case Intrinsic::objectsize: {
1080 // Lower all uses of llvm.objectsize.*
1081 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1082 Type *ReturnTy = CI->getType();
1083 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
1084
1085 // Substituting this can cause recursive simplifications, which can
1086 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1087 // happens.
1088 WeakVH IterHandle(CurInstIterator);
1089
1090 replaceAndRecursivelySimplify(CI, RetVal,
1091 TLI ? TLI->getDataLayout() : nullptr,
1092 TLInfo, ModifiedDT ? nullptr : DT);
1093
1094 // If the iterator instruction was recursively deleted, start over at the
1095 // start of the block.
1096 if (IterHandle != CurInstIterator) {
1097 CurInstIterator = BB->begin();
1098 SunkAddrs.clear();
1099 }
1100 return true;
1101 }
1102 case Intrinsic::masked_load: {
1103 // Scalarize unsupported vector masked load
1104 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1105 ScalarizeMaskedLoad(CI);
1106 ModifiedDT = true;
1107 return true;
1108 }
1109 return false;
1110 }
1111 case Intrinsic::masked_store: {
1112 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1113 ScalarizeMaskedStore(CI);
1114 ModifiedDT = true;
1115 return true;
1116 }
1117 return false;
1118 }
1119 }
1120
1121 if (TLI) {
1122 SmallVector<Value*, 2> PtrOps;
1123 Type *AccessTy;
1124 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
1125 while (!PtrOps.empty())
1126 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
1127 return true;
1128 }
1129 }
1130
1131 // From here on out we're working with named functions.
1132 if (!CI->getCalledFunction()) return false;
1133
1134 // We'll need DataLayout from here on out.
1135 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
1136 if (!TD) return false;
1137
1138 // Lower all default uses of _chk calls. This is very similar
1139 // to what InstCombineCalls does, but here we are only lowering calls
1140 // to fortified library functions (e.g. __memcpy_chk) that have the default
1141 // "don't know" as the objectsize. Anything else should be left alone.
1142 FortifiedLibCallSimplifier Simplifier(TD, TLInfo, true);
1143 if (Value *V = Simplifier.optimizeCall(CI)) {
1144 CI->replaceAllUsesWith(V);
1145 CI->eraseFromParent();
1146 return true;
1147 }
1148 return false;
1149 }
1150
1151 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1152 /// instructions to the predecessor to enable tail call optimizations. The
1153 /// case it is currently looking for is:
1154 /// @code
1155 /// bb0:
1156 /// %tmp0 = tail call i32 @f0()
1157 /// br label %return
1158 /// bb1:
1159 /// %tmp1 = tail call i32 @f1()
1160 /// br label %return
1161 /// bb2:
1162 /// %tmp2 = tail call i32 @f2()
1163 /// br label %return
1164 /// return:
1165 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1166 /// ret i32 %retval
1167 /// @endcode
1168 ///
1169 /// =>
1170 ///
1171 /// @code
1172 /// bb0:
1173 /// %tmp0 = tail call i32 @f0()
1174 /// ret i32 %tmp0
1175 /// bb1:
1176 /// %tmp1 = tail call i32 @f1()
1177 /// ret i32 %tmp1
1178 /// bb2:
1179 /// %tmp2 = tail call i32 @f2()
1180 /// ret i32 %tmp2
1181 /// @endcode
DupRetToEnableTailCallOpts(BasicBlock * BB)1182 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
1183 if (!TLI)
1184 return false;
1185
1186 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1187 if (!RI)
1188 return false;
1189
1190 PHINode *PN = nullptr;
1191 BitCastInst *BCI = nullptr;
1192 Value *V = RI->getReturnValue();
1193 if (V) {
1194 BCI = dyn_cast<BitCastInst>(V);
1195 if (BCI)
1196 V = BCI->getOperand(0);
1197
1198 PN = dyn_cast<PHINode>(V);
1199 if (!PN)
1200 return false;
1201 }
1202
1203 if (PN && PN->getParent() != BB)
1204 return false;
1205
1206 // It's not safe to eliminate the sign / zero extension of the return value.
1207 // See llvm::isInTailCallPosition().
1208 const Function *F = BB->getParent();
1209 AttributeSet CallerAttrs = F->getAttributes();
1210 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1211 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
1212 return false;
1213
1214 // Make sure there are no instructions between the PHI and return, or that the
1215 // return is the first instruction in the block.
1216 if (PN) {
1217 BasicBlock::iterator BI = BB->begin();
1218 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
1219 if (&*BI == BCI)
1220 // Also skip over the bitcast.
1221 ++BI;
1222 if (&*BI != RI)
1223 return false;
1224 } else {
1225 BasicBlock::iterator BI = BB->begin();
1226 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1227 if (&*BI != RI)
1228 return false;
1229 }
1230
1231 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1232 /// call.
1233 SmallVector<CallInst*, 4> TailCalls;
1234 if (PN) {
1235 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1236 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1237 // Make sure the phi value is indeed produced by the tail call.
1238 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1239 TLI->mayBeEmittedAsTailCall(CI))
1240 TailCalls.push_back(CI);
1241 }
1242 } else {
1243 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1244 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1245 if (!VisitedBBs.insert(*PI).second)
1246 continue;
1247
1248 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1249 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1250 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1251 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1252 if (RI == RE)
1253 continue;
1254
1255 CallInst *CI = dyn_cast<CallInst>(&*RI);
1256 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1257 TailCalls.push_back(CI);
1258 }
1259 }
1260
1261 bool Changed = false;
1262 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1263 CallInst *CI = TailCalls[i];
1264 CallSite CS(CI);
1265
1266 // Conservatively require the attributes of the call to match those of the
1267 // return. Ignore noalias because it doesn't affect the call sequence.
1268 AttributeSet CalleeAttrs = CS.getAttributes();
1269 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1270 removeAttribute(Attribute::NoAlias) !=
1271 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1272 removeAttribute(Attribute::NoAlias))
1273 continue;
1274
1275 // Make sure the call instruction is followed by an unconditional branch to
1276 // the return block.
1277 BasicBlock *CallBB = CI->getParent();
1278 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1279 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1280 continue;
1281
1282 // Duplicate the return into CallBB.
1283 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1284 ModifiedDT = Changed = true;
1285 ++NumRetsDup;
1286 }
1287
1288 // If we eliminated all predecessors of the block, delete the block now.
1289 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1290 BB->eraseFromParent();
1291
1292 return Changed;
1293 }
1294
1295 //===----------------------------------------------------------------------===//
1296 // Memory Optimization
1297 //===----------------------------------------------------------------------===//
1298
1299 namespace {
1300
1301 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1302 /// which holds actual Value*'s for register values.
1303 struct ExtAddrMode : public TargetLowering::AddrMode {
1304 Value *BaseReg;
1305 Value *ScaledReg;
ExtAddrMode__anon8f33d8c30211::ExtAddrMode1306 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1307 void print(raw_ostream &OS) const;
1308 void dump() const;
1309
operator ==__anon8f33d8c30211::ExtAddrMode1310 bool operator==(const ExtAddrMode& O) const {
1311 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1312 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1313 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1314 }
1315 };
1316
1317 #ifndef NDEBUG
operator <<(raw_ostream & OS,const ExtAddrMode & AM)1318 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1319 AM.print(OS);
1320 return OS;
1321 }
1322 #endif
1323
print(raw_ostream & OS) const1324 void ExtAddrMode::print(raw_ostream &OS) const {
1325 bool NeedPlus = false;
1326 OS << "[";
1327 if (BaseGV) {
1328 OS << (NeedPlus ? " + " : "")
1329 << "GV:";
1330 BaseGV->printAsOperand(OS, /*PrintType=*/false);
1331 NeedPlus = true;
1332 }
1333
1334 if (BaseOffs) {
1335 OS << (NeedPlus ? " + " : "")
1336 << BaseOffs;
1337 NeedPlus = true;
1338 }
1339
1340 if (BaseReg) {
1341 OS << (NeedPlus ? " + " : "")
1342 << "Base:";
1343 BaseReg->printAsOperand(OS, /*PrintType=*/false);
1344 NeedPlus = true;
1345 }
1346 if (Scale) {
1347 OS << (NeedPlus ? " + " : "")
1348 << Scale << "*";
1349 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1350 }
1351
1352 OS << ']';
1353 }
1354
1355 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const1356 void ExtAddrMode::dump() const {
1357 print(dbgs());
1358 dbgs() << '\n';
1359 }
1360 #endif
1361
1362 /// \brief This class provides transaction based operation on the IR.
1363 /// Every change made through this class is recorded in the internal state and
1364 /// can be undone (rollback) until commit is called.
1365 class TypePromotionTransaction {
1366
1367 /// \brief This represents the common interface of the individual transaction.
1368 /// Each class implements the logic for doing one specific modification on
1369 /// the IR via the TypePromotionTransaction.
1370 class TypePromotionAction {
1371 protected:
1372 /// The Instruction modified.
1373 Instruction *Inst;
1374
1375 public:
1376 /// \brief Constructor of the action.
1377 /// The constructor performs the related action on the IR.
TypePromotionAction(Instruction * Inst)1378 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1379
~TypePromotionAction()1380 virtual ~TypePromotionAction() {}
1381
1382 /// \brief Undo the modification done by this action.
1383 /// When this method is called, the IR must be in the same state as it was
1384 /// before this action was applied.
1385 /// \pre Undoing the action works if and only if the IR is in the exact same
1386 /// state as it was directly after this action was applied.
1387 virtual void undo() = 0;
1388
1389 /// \brief Advocate every change made by this action.
1390 /// When the results on the IR of the action are to be kept, it is important
1391 /// to call this function, otherwise hidden information may be kept forever.
commit()1392 virtual void commit() {
1393 // Nothing to be done, this action is not doing anything.
1394 }
1395 };
1396
1397 /// \brief Utility to remember the position of an instruction.
1398 class InsertionHandler {
1399 /// Position of an instruction.
1400 /// Either an instruction:
1401 /// - Is the first in a basic block: BB is used.
1402 /// - Has a previous instructon: PrevInst is used.
1403 union {
1404 Instruction *PrevInst;
1405 BasicBlock *BB;
1406 } Point;
1407 /// Remember whether or not the instruction had a previous instruction.
1408 bool HasPrevInstruction;
1409
1410 public:
1411 /// \brief Record the position of \p Inst.
InsertionHandler(Instruction * Inst)1412 InsertionHandler(Instruction *Inst) {
1413 BasicBlock::iterator It = Inst;
1414 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1415 if (HasPrevInstruction)
1416 Point.PrevInst = --It;
1417 else
1418 Point.BB = Inst->getParent();
1419 }
1420
1421 /// \brief Insert \p Inst at the recorded position.
insert(Instruction * Inst)1422 void insert(Instruction *Inst) {
1423 if (HasPrevInstruction) {
1424 if (Inst->getParent())
1425 Inst->removeFromParent();
1426 Inst->insertAfter(Point.PrevInst);
1427 } else {
1428 Instruction *Position = Point.BB->getFirstInsertionPt();
1429 if (Inst->getParent())
1430 Inst->moveBefore(Position);
1431 else
1432 Inst->insertBefore(Position);
1433 }
1434 }
1435 };
1436
1437 /// \brief Move an instruction before another.
1438 class InstructionMoveBefore : public TypePromotionAction {
1439 /// Original position of the instruction.
1440 InsertionHandler Position;
1441
1442 public:
1443 /// \brief Move \p Inst before \p Before.
InstructionMoveBefore(Instruction * Inst,Instruction * Before)1444 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1445 : TypePromotionAction(Inst), Position(Inst) {
1446 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1447 Inst->moveBefore(Before);
1448 }
1449
1450 /// \brief Move the instruction back to its original position.
undo()1451 void undo() override {
1452 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1453 Position.insert(Inst);
1454 }
1455 };
1456
1457 /// \brief Set the operand of an instruction with a new value.
1458 class OperandSetter : public TypePromotionAction {
1459 /// Original operand of the instruction.
1460 Value *Origin;
1461 /// Index of the modified instruction.
1462 unsigned Idx;
1463
1464 public:
1465 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
OperandSetter(Instruction * Inst,unsigned Idx,Value * NewVal)1466 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1467 : TypePromotionAction(Inst), Idx(Idx) {
1468 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1469 << "for:" << *Inst << "\n"
1470 << "with:" << *NewVal << "\n");
1471 Origin = Inst->getOperand(Idx);
1472 Inst->setOperand(Idx, NewVal);
1473 }
1474
1475 /// \brief Restore the original value of the instruction.
undo()1476 void undo() override {
1477 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1478 << "for: " << *Inst << "\n"
1479 << "with: " << *Origin << "\n");
1480 Inst->setOperand(Idx, Origin);
1481 }
1482 };
1483
1484 /// \brief Hide the operands of an instruction.
1485 /// Do as if this instruction was not using any of its operands.
1486 class OperandsHider : public TypePromotionAction {
1487 /// The list of original operands.
1488 SmallVector<Value *, 4> OriginalValues;
1489
1490 public:
1491 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
OperandsHider(Instruction * Inst)1492 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1493 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1494 unsigned NumOpnds = Inst->getNumOperands();
1495 OriginalValues.reserve(NumOpnds);
1496 for (unsigned It = 0; It < NumOpnds; ++It) {
1497 // Save the current operand.
1498 Value *Val = Inst->getOperand(It);
1499 OriginalValues.push_back(Val);
1500 // Set a dummy one.
1501 // We could use OperandSetter here, but that would implied an overhead
1502 // that we are not willing to pay.
1503 Inst->setOperand(It, UndefValue::get(Val->getType()));
1504 }
1505 }
1506
1507 /// \brief Restore the original list of uses.
undo()1508 void undo() override {
1509 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1510 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1511 Inst->setOperand(It, OriginalValues[It]);
1512 }
1513 };
1514
1515 /// \brief Build a truncate instruction.
1516 class TruncBuilder : public TypePromotionAction {
1517 Value *Val;
1518 public:
1519 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1520 /// result.
1521 /// trunc Opnd to Ty.
TruncBuilder(Instruction * Opnd,Type * Ty)1522 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1523 IRBuilder<> Builder(Opnd);
1524 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1525 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
1526 }
1527
1528 /// \brief Get the built value.
getBuiltValue()1529 Value *getBuiltValue() { return Val; }
1530
1531 /// \brief Remove the built instruction.
undo()1532 void undo() override {
1533 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1534 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1535 IVal->eraseFromParent();
1536 }
1537 };
1538
1539 /// \brief Build a sign extension instruction.
1540 class SExtBuilder : public TypePromotionAction {
1541 Value *Val;
1542 public:
1543 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1544 /// result.
1545 /// sext Opnd to Ty.
SExtBuilder(Instruction * InsertPt,Value * Opnd,Type * Ty)1546 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1547 : TypePromotionAction(InsertPt) {
1548 IRBuilder<> Builder(InsertPt);
1549 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1550 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
1551 }
1552
1553 /// \brief Get the built value.
getBuiltValue()1554 Value *getBuiltValue() { return Val; }
1555
1556 /// \brief Remove the built instruction.
undo()1557 void undo() override {
1558 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1559 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1560 IVal->eraseFromParent();
1561 }
1562 };
1563
1564 /// \brief Build a zero extension instruction.
1565 class ZExtBuilder : public TypePromotionAction {
1566 Value *Val;
1567 public:
1568 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1569 /// result.
1570 /// zext Opnd to Ty.
ZExtBuilder(Instruction * InsertPt,Value * Opnd,Type * Ty)1571 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1572 : TypePromotionAction(InsertPt) {
1573 IRBuilder<> Builder(InsertPt);
1574 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1575 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1576 }
1577
1578 /// \brief Get the built value.
getBuiltValue()1579 Value *getBuiltValue() { return Val; }
1580
1581 /// \brief Remove the built instruction.
undo()1582 void undo() override {
1583 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1584 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1585 IVal->eraseFromParent();
1586 }
1587 };
1588
1589 /// \brief Mutate an instruction to another type.
1590 class TypeMutator : public TypePromotionAction {
1591 /// Record the original type.
1592 Type *OrigTy;
1593
1594 public:
1595 /// \brief Mutate the type of \p Inst into \p NewTy.
TypeMutator(Instruction * Inst,Type * NewTy)1596 TypeMutator(Instruction *Inst, Type *NewTy)
1597 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1598 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1599 << "\n");
1600 Inst->mutateType(NewTy);
1601 }
1602
1603 /// \brief Mutate the instruction back to its original type.
undo()1604 void undo() override {
1605 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1606 << "\n");
1607 Inst->mutateType(OrigTy);
1608 }
1609 };
1610
1611 /// \brief Replace the uses of an instruction by another instruction.
1612 class UsesReplacer : public TypePromotionAction {
1613 /// Helper structure to keep track of the replaced uses.
1614 struct InstructionAndIdx {
1615 /// The instruction using the instruction.
1616 Instruction *Inst;
1617 /// The index where this instruction is used for Inst.
1618 unsigned Idx;
InstructionAndIdx__anon8f33d8c30211::TypePromotionTransaction::UsesReplacer::InstructionAndIdx1619 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1620 : Inst(Inst), Idx(Idx) {}
1621 };
1622
1623 /// Keep track of the original uses (pair Instruction, Index).
1624 SmallVector<InstructionAndIdx, 4> OriginalUses;
1625 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1626
1627 public:
1628 /// \brief Replace all the use of \p Inst by \p New.
UsesReplacer(Instruction * Inst,Value * New)1629 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1630 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1631 << "\n");
1632 // Record the original uses.
1633 for (Use &U : Inst->uses()) {
1634 Instruction *UserI = cast<Instruction>(U.getUser());
1635 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1636 }
1637 // Now, we can replace the uses.
1638 Inst->replaceAllUsesWith(New);
1639 }
1640
1641 /// \brief Reassign the original uses of Inst to Inst.
undo()1642 void undo() override {
1643 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1644 for (use_iterator UseIt = OriginalUses.begin(),
1645 EndIt = OriginalUses.end();
1646 UseIt != EndIt; ++UseIt) {
1647 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1648 }
1649 }
1650 };
1651
1652 /// \brief Remove an instruction from the IR.
1653 class InstructionRemover : public TypePromotionAction {
1654 /// Original position of the instruction.
1655 InsertionHandler Inserter;
1656 /// Helper structure to hide all the link to the instruction. In other
1657 /// words, this helps to do as if the instruction was removed.
1658 OperandsHider Hider;
1659 /// Keep track of the uses replaced, if any.
1660 UsesReplacer *Replacer;
1661
1662 public:
1663 /// \brief Remove all reference of \p Inst and optinally replace all its
1664 /// uses with New.
1665 /// \pre If !Inst->use_empty(), then New != nullptr
InstructionRemover(Instruction * Inst,Value * New=nullptr)1666 InstructionRemover(Instruction *Inst, Value *New = nullptr)
1667 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1668 Replacer(nullptr) {
1669 if (New)
1670 Replacer = new UsesReplacer(Inst, New);
1671 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1672 Inst->removeFromParent();
1673 }
1674
~InstructionRemover()1675 ~InstructionRemover() { delete Replacer; }
1676
1677 /// \brief Really remove the instruction.
commit()1678 void commit() override { delete Inst; }
1679
1680 /// \brief Resurrect the instruction and reassign it to the proper uses if
1681 /// new value was provided when build this action.
undo()1682 void undo() override {
1683 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1684 Inserter.insert(Inst);
1685 if (Replacer)
1686 Replacer->undo();
1687 Hider.undo();
1688 }
1689 };
1690
1691 public:
1692 /// Restoration point.
1693 /// The restoration point is a pointer to an action instead of an iterator
1694 /// because the iterator may be invalidated but not the pointer.
1695 typedef const TypePromotionAction *ConstRestorationPt;
1696 /// Advocate every changes made in that transaction.
1697 void commit();
1698 /// Undo all the changes made after the given point.
1699 void rollback(ConstRestorationPt Point);
1700 /// Get the current restoration point.
1701 ConstRestorationPt getRestorationPoint() const;
1702
1703 /// \name API for IR modification with state keeping to support rollback.
1704 /// @{
1705 /// Same as Instruction::setOperand.
1706 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1707 /// Same as Instruction::eraseFromParent.
1708 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1709 /// Same as Value::replaceAllUsesWith.
1710 void replaceAllUsesWith(Instruction *Inst, Value *New);
1711 /// Same as Value::mutateType.
1712 void mutateType(Instruction *Inst, Type *NewTy);
1713 /// Same as IRBuilder::createTrunc.
1714 Value *createTrunc(Instruction *Opnd, Type *Ty);
1715 /// Same as IRBuilder::createSExt.
1716 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1717 /// Same as IRBuilder::createZExt.
1718 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
1719 /// Same as Instruction::moveBefore.
1720 void moveBefore(Instruction *Inst, Instruction *Before);
1721 /// @}
1722
1723 private:
1724 /// The ordered list of actions made so far.
1725 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1726 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1727 };
1728
setOperand(Instruction * Inst,unsigned Idx,Value * NewVal)1729 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1730 Value *NewVal) {
1731 Actions.push_back(
1732 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1733 }
1734
eraseInstruction(Instruction * Inst,Value * NewVal)1735 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1736 Value *NewVal) {
1737 Actions.push_back(
1738 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1739 }
1740
replaceAllUsesWith(Instruction * Inst,Value * New)1741 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1742 Value *New) {
1743 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1744 }
1745
mutateType(Instruction * Inst,Type * NewTy)1746 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1747 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1748 }
1749
createTrunc(Instruction * Opnd,Type * Ty)1750 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1751 Type *Ty) {
1752 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1753 Value *Val = Ptr->getBuiltValue();
1754 Actions.push_back(std::move(Ptr));
1755 return Val;
1756 }
1757
createSExt(Instruction * Inst,Value * Opnd,Type * Ty)1758 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1759 Value *Opnd, Type *Ty) {
1760 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1761 Value *Val = Ptr->getBuiltValue();
1762 Actions.push_back(std::move(Ptr));
1763 return Val;
1764 }
1765
createZExt(Instruction * Inst,Value * Opnd,Type * Ty)1766 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1767 Value *Opnd, Type *Ty) {
1768 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
1769 Value *Val = Ptr->getBuiltValue();
1770 Actions.push_back(std::move(Ptr));
1771 return Val;
1772 }
1773
moveBefore(Instruction * Inst,Instruction * Before)1774 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1775 Instruction *Before) {
1776 Actions.push_back(
1777 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1778 }
1779
1780 TypePromotionTransaction::ConstRestorationPt
getRestorationPoint() const1781 TypePromotionTransaction::getRestorationPoint() const {
1782 return !Actions.empty() ? Actions.back().get() : nullptr;
1783 }
1784
commit()1785 void TypePromotionTransaction::commit() {
1786 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1787 ++It)
1788 (*It)->commit();
1789 Actions.clear();
1790 }
1791
rollback(TypePromotionTransaction::ConstRestorationPt Point)1792 void TypePromotionTransaction::rollback(
1793 TypePromotionTransaction::ConstRestorationPt Point) {
1794 while (!Actions.empty() && Point != Actions.back().get()) {
1795 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1796 Curr->undo();
1797 }
1798 }
1799
1800 /// \brief A helper class for matching addressing modes.
1801 ///
1802 /// This encapsulates the logic for matching the target-legal addressing modes.
1803 class AddressingModeMatcher {
1804 SmallVectorImpl<Instruction*> &AddrModeInsts;
1805 const TargetLowering &TLI;
1806
1807 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1808 /// the memory instruction that we're computing this address for.
1809 Type *AccessTy;
1810 Instruction *MemoryInst;
1811
1812 /// AddrMode - This is the addressing mode that we're building up. This is
1813 /// part of the return value of this addressing mode matching stuff.
1814 ExtAddrMode &AddrMode;
1815
1816 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1817 const SetOfInstrs &InsertedTruncs;
1818 /// A map from the instructions to their type before promotion.
1819 InstrToOrigTy &PromotedInsts;
1820 /// The ongoing transaction where every action should be registered.
1821 TypePromotionTransaction &TPT;
1822
1823 /// IgnoreProfitability - This is set to true when we should not do
1824 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1825 /// always returns true.
1826 bool IgnoreProfitability;
1827
AddressingModeMatcher(SmallVectorImpl<Instruction * > & AMI,const TargetLowering & T,Type * AT,Instruction * MI,ExtAddrMode & AM,const SetOfInstrs & InsertedTruncs,InstrToOrigTy & PromotedInsts,TypePromotionTransaction & TPT)1828 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1829 const TargetLowering &T, Type *AT,
1830 Instruction *MI, ExtAddrMode &AM,
1831 const SetOfInstrs &InsertedTruncs,
1832 InstrToOrigTy &PromotedInsts,
1833 TypePromotionTransaction &TPT)
1834 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1835 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1836 IgnoreProfitability = false;
1837 }
1838 public:
1839
1840 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1841 /// give an access type of AccessTy. This returns a list of involved
1842 /// instructions in AddrModeInsts.
1843 /// \p InsertedTruncs The truncate instruction inserted by other
1844 /// CodeGenPrepare
1845 /// optimizations.
1846 /// \p PromotedInsts maps the instructions to their type before promotion.
1847 /// \p The ongoing transaction where every action should be registered.
Match(Value * V,Type * AccessTy,Instruction * MemoryInst,SmallVectorImpl<Instruction * > & AddrModeInsts,const TargetLowering & TLI,const SetOfInstrs & InsertedTruncs,InstrToOrigTy & PromotedInsts,TypePromotionTransaction & TPT)1848 static ExtAddrMode Match(Value *V, Type *AccessTy,
1849 Instruction *MemoryInst,
1850 SmallVectorImpl<Instruction*> &AddrModeInsts,
1851 const TargetLowering &TLI,
1852 const SetOfInstrs &InsertedTruncs,
1853 InstrToOrigTy &PromotedInsts,
1854 TypePromotionTransaction &TPT) {
1855 ExtAddrMode Result;
1856
1857 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1858 MemoryInst, Result, InsertedTruncs,
1859 PromotedInsts, TPT).MatchAddr(V, 0);
1860 (void)Success; assert(Success && "Couldn't select *anything*?");
1861 return Result;
1862 }
1863 private:
1864 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1865 bool MatchAddr(Value *V, unsigned Depth);
1866 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1867 bool *MovedAway = nullptr);
1868 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1869 ExtAddrMode &AMBefore,
1870 ExtAddrMode &AMAfter);
1871 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1872 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1873 Value *PromotedOperand) const;
1874 };
1875
1876 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1877 /// Return true and update AddrMode if this addr mode is legal for the target,
1878 /// false if not.
MatchScaledValue(Value * ScaleReg,int64_t Scale,unsigned Depth)1879 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1880 unsigned Depth) {
1881 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1882 // mode. Just process that directly.
1883 if (Scale == 1)
1884 return MatchAddr(ScaleReg, Depth);
1885
1886 // If the scale is 0, it takes nothing to add this.
1887 if (Scale == 0)
1888 return true;
1889
1890 // If we already have a scale of this value, we can add to it, otherwise, we
1891 // need an available scale field.
1892 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1893 return false;
1894
1895 ExtAddrMode TestAddrMode = AddrMode;
1896
1897 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1898 // [A+B + A*7] -> [B+A*8].
1899 TestAddrMode.Scale += Scale;
1900 TestAddrMode.ScaledReg = ScaleReg;
1901
1902 // If the new address isn't legal, bail out.
1903 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1904 return false;
1905
1906 // It was legal, so commit it.
1907 AddrMode = TestAddrMode;
1908
1909 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1910 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1911 // X*Scale + C*Scale to addr mode.
1912 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
1913 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1914 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1915 TestAddrMode.ScaledReg = AddLHS;
1916 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1917
1918 // If this addressing mode is legal, commit it and remember that we folded
1919 // this instruction.
1920 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1921 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1922 AddrMode = TestAddrMode;
1923 return true;
1924 }
1925 }
1926
1927 // Otherwise, not (x+c)*scale, just return what we have.
1928 return true;
1929 }
1930
1931 /// MightBeFoldableInst - This is a little filter, which returns true if an
1932 /// addressing computation involving I might be folded into a load/store
1933 /// accessing it. This doesn't need to be perfect, but needs to accept at least
1934 /// the set of instructions that MatchOperationAddr can.
MightBeFoldableInst(Instruction * I)1935 static bool MightBeFoldableInst(Instruction *I) {
1936 switch (I->getOpcode()) {
1937 case Instruction::BitCast:
1938 case Instruction::AddrSpaceCast:
1939 // Don't touch identity bitcasts.
1940 if (I->getType() == I->getOperand(0)->getType())
1941 return false;
1942 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1943 case Instruction::PtrToInt:
1944 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1945 return true;
1946 case Instruction::IntToPtr:
1947 // We know the input is intptr_t, so this is foldable.
1948 return true;
1949 case Instruction::Add:
1950 return true;
1951 case Instruction::Mul:
1952 case Instruction::Shl:
1953 // Can only handle X*C and X << C.
1954 return isa<ConstantInt>(I->getOperand(1));
1955 case Instruction::GetElementPtr:
1956 return true;
1957 default:
1958 return false;
1959 }
1960 }
1961
1962 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
1963 /// \note \p Val is assumed to be the product of some type promotion.
1964 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
1965 /// to be legal, as the non-promoted value would have had the same state.
isPromotedInstructionLegal(const TargetLowering & TLI,Value * Val)1966 static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
1967 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
1968 if (!PromotedInst)
1969 return false;
1970 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1971 // If the ISDOpcode is undefined, it was undefined before the promotion.
1972 if (!ISDOpcode)
1973 return true;
1974 // Otherwise, check if the promoted instruction is legal or not.
1975 return TLI.isOperationLegalOrCustom(
1976 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
1977 }
1978
1979 /// \brief Hepler class to perform type promotion.
1980 class TypePromotionHelper {
1981 /// \brief Utility function to check whether or not a sign or zero extension
1982 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1983 /// either using the operands of \p Inst or promoting \p Inst.
1984 /// The type of the extension is defined by \p IsSExt.
1985 /// In other words, check if:
1986 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
1987 /// #1 Promotion applies:
1988 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
1989 /// #2 Operand reuses:
1990 /// ext opnd1 to ConsideredExtType.
1991 /// \p PromotedInsts maps the instructions to their type before promotion.
1992 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
1993 const InstrToOrigTy &PromotedInsts, bool IsSExt);
1994
1995 /// \brief Utility function to determine if \p OpIdx should be promoted when
1996 /// promoting \p Inst.
shouldExtOperand(const Instruction * Inst,int OpIdx)1997 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
1998 if (isa<SelectInst>(Inst) && OpIdx == 0)
1999 return false;
2000 return true;
2001 }
2002
2003 /// \brief Utility function to promote the operand of \p Ext when this
2004 /// operand is a promotable trunc or sext or zext.
2005 /// \p PromotedInsts maps the instructions to their type before promotion.
2006 /// \p CreatedInsts[out] contains how many non-free instructions have been
2007 /// created to promote the operand of Ext.
2008 /// Newly added extensions are inserted in \p Exts.
2009 /// Newly added truncates are inserted in \p Truncs.
2010 /// Should never be called directly.
2011 /// \return The promoted value which is used instead of Ext.
2012 static Value *promoteOperandForTruncAndAnyExt(
2013 Instruction *Ext, TypePromotionTransaction &TPT,
2014 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2015 SmallVectorImpl<Instruction *> *Exts,
2016 SmallVectorImpl<Instruction *> *Truncs);
2017
2018 /// \brief Utility function to promote the operand of \p Ext when this
2019 /// operand is promotable and is not a supported trunc or sext.
2020 /// \p PromotedInsts maps the instructions to their type before promotion.
2021 /// \p CreatedInsts[out] contains how many non-free instructions have been
2022 /// created to promote the operand of Ext.
2023 /// Newly added extensions are inserted in \p Exts.
2024 /// Newly added truncates are inserted in \p Truncs.
2025 /// Should never be called directly.
2026 /// \return The promoted value which is used instead of Ext.
2027 static Value *
2028 promoteOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2029 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2030 SmallVectorImpl<Instruction *> *Exts,
2031 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt);
2032
2033 /// \see promoteOperandForOther.
2034 static Value *
signExtendOperandForOther(Instruction * Ext,TypePromotionTransaction & TPT,InstrToOrigTy & PromotedInsts,unsigned & CreatedInsts,SmallVectorImpl<Instruction * > * Exts,SmallVectorImpl<Instruction * > * Truncs)2035 signExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2036 InstrToOrigTy &PromotedInsts,
2037 unsigned &CreatedInsts,
2038 SmallVectorImpl<Instruction *> *Exts,
2039 SmallVectorImpl<Instruction *> *Truncs) {
2040 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2041 Truncs, true);
2042 }
2043
2044 /// \see promoteOperandForOther.
2045 static Value *
zeroExtendOperandForOther(Instruction * Ext,TypePromotionTransaction & TPT,InstrToOrigTy & PromotedInsts,unsigned & CreatedInsts,SmallVectorImpl<Instruction * > * Exts,SmallVectorImpl<Instruction * > * Truncs)2046 zeroExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2047 InstrToOrigTy &PromotedInsts,
2048 unsigned &CreatedInsts,
2049 SmallVectorImpl<Instruction *> *Exts,
2050 SmallVectorImpl<Instruction *> *Truncs) {
2051 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2052 Truncs, false);
2053 }
2054
2055 public:
2056 /// Type for the utility function that promotes the operand of Ext.
2057 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
2058 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2059 SmallVectorImpl<Instruction *> *Exts,
2060 SmallVectorImpl<Instruction *> *Truncs);
2061 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2062 /// action to promote the operand of \p Ext instead of using Ext.
2063 /// \return NULL if no promotable action is possible with the current
2064 /// sign extension.
2065 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
2066 /// the others CodeGenPrepare optimizations. This information is important
2067 /// because we do not want to promote these instructions as CodeGenPrepare
2068 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2069 /// \p PromotedInsts maps the instructions to their type before promotion.
2070 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
2071 const TargetLowering &TLI,
2072 const InstrToOrigTy &PromotedInsts);
2073 };
2074
canGetThrough(const Instruction * Inst,Type * ConsideredExtType,const InstrToOrigTy & PromotedInsts,bool IsSExt)2075 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
2076 Type *ConsideredExtType,
2077 const InstrToOrigTy &PromotedInsts,
2078 bool IsSExt) {
2079 // The promotion helper does not know how to deal with vector types yet.
2080 // To be able to fix that, we would need to fix the places where we
2081 // statically extend, e.g., constants and such.
2082 if (Inst->getType()->isVectorTy())
2083 return false;
2084
2085 // We can always get through zext.
2086 if (isa<ZExtInst>(Inst))
2087 return true;
2088
2089 // sext(sext) is ok too.
2090 if (IsSExt && isa<SExtInst>(Inst))
2091 return true;
2092
2093 // We can get through binary operator, if it is legal. In other words, the
2094 // binary operator must have a nuw or nsw flag.
2095 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2096 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
2097 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2098 (IsSExt && BinOp->hasNoSignedWrap())))
2099 return true;
2100
2101 // Check if we can do the following simplification.
2102 // ext(trunc(opnd)) --> ext(opnd)
2103 if (!isa<TruncInst>(Inst))
2104 return false;
2105
2106 Value *OpndVal = Inst->getOperand(0);
2107 // Check if we can use this operand in the extension.
2108 // If the type is larger than the result type of the extension,
2109 // we cannot.
2110 if (!OpndVal->getType()->isIntegerTy() ||
2111 OpndVal->getType()->getIntegerBitWidth() >
2112 ConsideredExtType->getIntegerBitWidth())
2113 return false;
2114
2115 // If the operand of the truncate is not an instruction, we will not have
2116 // any information on the dropped bits.
2117 // (Actually we could for constant but it is not worth the extra logic).
2118 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2119 if (!Opnd)
2120 return false;
2121
2122 // Check if the source of the type is narrow enough.
2123 // I.e., check that trunc just drops extended bits of the same kind of
2124 // the extension.
2125 // #1 get the type of the operand and check the kind of the extended bits.
2126 const Type *OpndType;
2127 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
2128 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
2129 OpndType = It->second.Ty;
2130 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2131 OpndType = Opnd->getOperand(0)->getType();
2132 else
2133 return false;
2134
2135 // #2 check that the truncate just drop extended bits.
2136 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2137 return true;
2138
2139 return false;
2140 }
2141
getAction(Instruction * Ext,const SetOfInstrs & InsertedTruncs,const TargetLowering & TLI,const InstrToOrigTy & PromotedInsts)2142 TypePromotionHelper::Action TypePromotionHelper::getAction(
2143 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
2144 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
2145 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2146 "Unexpected instruction type");
2147 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2148 Type *ExtTy = Ext->getType();
2149 bool IsSExt = isa<SExtInst>(Ext);
2150 // If the operand of the extension is not an instruction, we cannot
2151 // get through.
2152 // If it, check we can get through.
2153 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
2154 return nullptr;
2155
2156 // Do not promote if the operand has been added by codegenprepare.
2157 // Otherwise, it means we are undoing an optimization that is likely to be
2158 // redone, thus causing potential infinite loop.
2159 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
2160 return nullptr;
2161
2162 // SExt or Trunc instructions.
2163 // Return the related handler.
2164 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2165 isa<ZExtInst>(ExtOpnd))
2166 return promoteOperandForTruncAndAnyExt;
2167
2168 // Regular instruction.
2169 // Abort early if we will have to insert non-free instructions.
2170 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
2171 return nullptr;
2172 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
2173 }
2174
promoteOperandForTruncAndAnyExt(llvm::Instruction * SExt,TypePromotionTransaction & TPT,InstrToOrigTy & PromotedInsts,unsigned & CreatedInsts,SmallVectorImpl<Instruction * > * Exts,SmallVectorImpl<Instruction * > * Truncs)2175 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
2176 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
2177 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2178 SmallVectorImpl<Instruction *> *Exts,
2179 SmallVectorImpl<Instruction *> *Truncs) {
2180 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2181 // get through it and this method should not be called.
2182 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
2183 Value *ExtVal = SExt;
2184 if (isa<ZExtInst>(SExtOpnd)) {
2185 // Replace s|zext(zext(opnd))
2186 // => zext(opnd).
2187 Value *ZExt =
2188 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2189 TPT.replaceAllUsesWith(SExt, ZExt);
2190 TPT.eraseInstruction(SExt);
2191 ExtVal = ZExt;
2192 } else {
2193 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2194 // => z|sext(opnd).
2195 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2196 }
2197 CreatedInsts = 0;
2198
2199 // Remove dead code.
2200 if (SExtOpnd->use_empty())
2201 TPT.eraseInstruction(SExtOpnd);
2202
2203 // Check if the extension is still needed.
2204 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
2205 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2206 if (ExtInst && Exts)
2207 Exts->push_back(ExtInst);
2208 return ExtVal;
2209 }
2210
2211 // At this point we have: ext ty opnd to ty.
2212 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2213 Value *NextVal = ExtInst->getOperand(0);
2214 TPT.eraseInstruction(ExtInst, NextVal);
2215 return NextVal;
2216 }
2217
promoteOperandForOther(Instruction * Ext,TypePromotionTransaction & TPT,InstrToOrigTy & PromotedInsts,unsigned & CreatedInsts,SmallVectorImpl<Instruction * > * Exts,SmallVectorImpl<Instruction * > * Truncs,bool IsSExt)2218 Value *TypePromotionHelper::promoteOperandForOther(
2219 Instruction *Ext, TypePromotionTransaction &TPT,
2220 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2221 SmallVectorImpl<Instruction *> *Exts,
2222 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt) {
2223 // By construction, the operand of Ext is an instruction. Otherwise we cannot
2224 // get through it and this method should not be called.
2225 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
2226 CreatedInsts = 0;
2227 if (!ExtOpnd->hasOneUse()) {
2228 // ExtOpnd will be promoted.
2229 // All its uses, but Ext, will need to use a truncated value of the
2230 // promoted version.
2231 // Create the truncate now.
2232 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
2233 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2234 ITrunc->removeFromParent();
2235 // Insert it just after the definition.
2236 ITrunc->insertAfter(ExtOpnd);
2237 if (Truncs)
2238 Truncs->push_back(ITrunc);
2239 }
2240
2241 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2242 // Restore the operand of Ext (which has been replace by the previous call
2243 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
2244 TPT.setOperand(Ext, 0, ExtOpnd);
2245 }
2246
2247 // Get through the Instruction:
2248 // 1. Update its type.
2249 // 2. Replace the uses of Ext by Inst.
2250 // 3. Extend each operand that needs to be extended.
2251
2252 // Remember the original type of the instruction before promotion.
2253 // This is useful to know that the high bits are sign extended bits.
2254 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2255 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
2256 // Step #1.
2257 TPT.mutateType(ExtOpnd, Ext->getType());
2258 // Step #2.
2259 TPT.replaceAllUsesWith(Ext, ExtOpnd);
2260 // Step #3.
2261 Instruction *ExtForOpnd = Ext;
2262
2263 DEBUG(dbgs() << "Propagate Ext to operands\n");
2264 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
2265 ++OpIdx) {
2266 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2267 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2268 !shouldExtOperand(ExtOpnd, OpIdx)) {
2269 DEBUG(dbgs() << "No need to propagate\n");
2270 continue;
2271 }
2272 // Check if we can statically extend the operand.
2273 Value *Opnd = ExtOpnd->getOperand(OpIdx);
2274 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
2275 DEBUG(dbgs() << "Statically extend\n");
2276 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2277 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2278 : Cst->getValue().zext(BitWidth);
2279 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
2280 continue;
2281 }
2282 // UndefValue are typed, so we have to statically sign extend them.
2283 if (isa<UndefValue>(Opnd)) {
2284 DEBUG(dbgs() << "Statically extend\n");
2285 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
2286 continue;
2287 }
2288
2289 // Otherwise we have to explicity sign extend the operand.
2290 // Check if Ext was reused to extend an operand.
2291 if (!ExtForOpnd) {
2292 // If yes, create a new one.
2293 DEBUG(dbgs() << "More operands to ext\n");
2294 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2295 : TPT.createZExt(Ext, Opnd, Ext->getType());
2296 if (!isa<Instruction>(ValForExtOpnd)) {
2297 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2298 continue;
2299 }
2300 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
2301 ++CreatedInsts;
2302 }
2303 if (Exts)
2304 Exts->push_back(ExtForOpnd);
2305 TPT.setOperand(ExtForOpnd, 0, Opnd);
2306
2307 // Move the sign extension before the insertion point.
2308 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2309 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2310 // If more sext are required, new instructions will have to be created.
2311 ExtForOpnd = nullptr;
2312 }
2313 if (ExtForOpnd == Ext) {
2314 DEBUG(dbgs() << "Extension is useless now\n");
2315 TPT.eraseInstruction(Ext);
2316 }
2317 return ExtOpnd;
2318 }
2319
2320 /// IsPromotionProfitable - Check whether or not promoting an instruction
2321 /// to a wider type was profitable.
2322 /// \p MatchedSize gives the number of instructions that have been matched
2323 /// in the addressing mode after the promotion was applied.
2324 /// \p SizeWithPromotion gives the number of created instructions for
2325 /// the promotion plus the number of instructions that have been
2326 /// matched in the addressing mode before the promotion.
2327 /// \p PromotedOperand is the value that has been promoted.
2328 /// \return True if the promotion is profitable, false otherwise.
2329 bool
IsPromotionProfitable(unsigned MatchedSize,unsigned SizeWithPromotion,Value * PromotedOperand) const2330 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2331 unsigned SizeWithPromotion,
2332 Value *PromotedOperand) const {
2333 // We folded less instructions than what we created to promote the operand.
2334 // This is not profitable.
2335 if (MatchedSize < SizeWithPromotion)
2336 return false;
2337 if (MatchedSize > SizeWithPromotion)
2338 return true;
2339 // The promotion is neutral but it may help folding the sign extension in
2340 // loads for instance.
2341 // Check that we did not create an illegal instruction.
2342 return isPromotedInstructionLegal(TLI, PromotedOperand);
2343 }
2344
2345 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2346 /// fold the operation into the addressing mode. If so, update the addressing
2347 /// mode and return true, otherwise return false without modifying AddrMode.
2348 /// If \p MovedAway is not NULL, it contains the information of whether or
2349 /// not AddrInst has to be folded into the addressing mode on success.
2350 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2351 /// because it has been moved away.
2352 /// Thus AddrInst must not be added in the matched instructions.
2353 /// This state can happen when AddrInst is a sext, since it may be moved away.
2354 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2355 /// not be referenced anymore.
MatchOperationAddr(User * AddrInst,unsigned Opcode,unsigned Depth,bool * MovedAway)2356 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2357 unsigned Depth,
2358 bool *MovedAway) {
2359 // Avoid exponential behavior on extremely deep expression trees.
2360 if (Depth >= 5) return false;
2361
2362 // By default, all matched instructions stay in place.
2363 if (MovedAway)
2364 *MovedAway = false;
2365
2366 switch (Opcode) {
2367 case Instruction::PtrToInt:
2368 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2369 return MatchAddr(AddrInst->getOperand(0), Depth);
2370 case Instruction::IntToPtr:
2371 // This inttoptr is a no-op if the integer type is pointer sized.
2372 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
2373 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
2374 return MatchAddr(AddrInst->getOperand(0), Depth);
2375 return false;
2376 case Instruction::BitCast:
2377 case Instruction::AddrSpaceCast:
2378 // BitCast is always a noop, and we can handle it as long as it is
2379 // int->int or pointer->pointer (we don't want int<->fp or something).
2380 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2381 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2382 // Don't touch identity bitcasts. These were probably put here by LSR,
2383 // and we don't want to mess around with them. Assume it knows what it
2384 // is doing.
2385 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2386 return MatchAddr(AddrInst->getOperand(0), Depth);
2387 return false;
2388 case Instruction::Add: {
2389 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2390 ExtAddrMode BackupAddrMode = AddrMode;
2391 unsigned OldSize = AddrModeInsts.size();
2392 // Start a transaction at this point.
2393 // The LHS may match but not the RHS.
2394 // Therefore, we need a higher level restoration point to undo partially
2395 // matched operation.
2396 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2397 TPT.getRestorationPoint();
2398
2399 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2400 MatchAddr(AddrInst->getOperand(0), Depth+1))
2401 return true;
2402
2403 // Restore the old addr mode info.
2404 AddrMode = BackupAddrMode;
2405 AddrModeInsts.resize(OldSize);
2406 TPT.rollback(LastKnownGood);
2407
2408 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2409 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2410 MatchAddr(AddrInst->getOperand(1), Depth+1))
2411 return true;
2412
2413 // Otherwise we definitely can't merge the ADD in.
2414 AddrMode = BackupAddrMode;
2415 AddrModeInsts.resize(OldSize);
2416 TPT.rollback(LastKnownGood);
2417 break;
2418 }
2419 //case Instruction::Or:
2420 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2421 //break;
2422 case Instruction::Mul:
2423 case Instruction::Shl: {
2424 // Can only handle X*C and X << C.
2425 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2426 if (!RHS)
2427 return false;
2428 int64_t Scale = RHS->getSExtValue();
2429 if (Opcode == Instruction::Shl)
2430 Scale = 1LL << Scale;
2431
2432 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2433 }
2434 case Instruction::GetElementPtr: {
2435 // Scan the GEP. We check it if it contains constant offsets and at most
2436 // one variable offset.
2437 int VariableOperand = -1;
2438 unsigned VariableScale = 0;
2439
2440 int64_t ConstantOffset = 0;
2441 const DataLayout *TD = TLI.getDataLayout();
2442 gep_type_iterator GTI = gep_type_begin(AddrInst);
2443 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2444 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2445 const StructLayout *SL = TD->getStructLayout(STy);
2446 unsigned Idx =
2447 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2448 ConstantOffset += SL->getElementOffset(Idx);
2449 } else {
2450 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2451 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2452 ConstantOffset += CI->getSExtValue()*TypeSize;
2453 } else if (TypeSize) { // Scales of zero don't do anything.
2454 // We only allow one variable index at the moment.
2455 if (VariableOperand != -1)
2456 return false;
2457
2458 // Remember the variable index.
2459 VariableOperand = i;
2460 VariableScale = TypeSize;
2461 }
2462 }
2463 }
2464
2465 // A common case is for the GEP to only do a constant offset. In this case,
2466 // just add it to the disp field and check validity.
2467 if (VariableOperand == -1) {
2468 AddrMode.BaseOffs += ConstantOffset;
2469 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2470 // Check to see if we can fold the base pointer in too.
2471 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2472 return true;
2473 }
2474 AddrMode.BaseOffs -= ConstantOffset;
2475 return false;
2476 }
2477
2478 // Save the valid addressing mode in case we can't match.
2479 ExtAddrMode BackupAddrMode = AddrMode;
2480 unsigned OldSize = AddrModeInsts.size();
2481
2482 // See if the scale and offset amount is valid for this target.
2483 AddrMode.BaseOffs += ConstantOffset;
2484
2485 // Match the base operand of the GEP.
2486 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2487 // If it couldn't be matched, just stuff the value in a register.
2488 if (AddrMode.HasBaseReg) {
2489 AddrMode = BackupAddrMode;
2490 AddrModeInsts.resize(OldSize);
2491 return false;
2492 }
2493 AddrMode.HasBaseReg = true;
2494 AddrMode.BaseReg = AddrInst->getOperand(0);
2495 }
2496
2497 // Match the remaining variable portion of the GEP.
2498 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2499 Depth)) {
2500 // If it couldn't be matched, try stuffing the base into a register
2501 // instead of matching it, and retrying the match of the scale.
2502 AddrMode = BackupAddrMode;
2503 AddrModeInsts.resize(OldSize);
2504 if (AddrMode.HasBaseReg)
2505 return false;
2506 AddrMode.HasBaseReg = true;
2507 AddrMode.BaseReg = AddrInst->getOperand(0);
2508 AddrMode.BaseOffs += ConstantOffset;
2509 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2510 VariableScale, Depth)) {
2511 // If even that didn't work, bail.
2512 AddrMode = BackupAddrMode;
2513 AddrModeInsts.resize(OldSize);
2514 return false;
2515 }
2516 }
2517
2518 return true;
2519 }
2520 case Instruction::SExt:
2521 case Instruction::ZExt: {
2522 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2523 if (!Ext)
2524 return false;
2525
2526 // Try to move this ext out of the way of the addressing mode.
2527 // Ask for a method for doing so.
2528 TypePromotionHelper::Action TPH =
2529 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
2530 if (!TPH)
2531 return false;
2532
2533 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2534 TPT.getRestorationPoint();
2535 unsigned CreatedInsts = 0;
2536 Value *PromotedOperand =
2537 TPH(Ext, TPT, PromotedInsts, CreatedInsts, nullptr, nullptr);
2538 // SExt has been moved away.
2539 // Thus either it will be rematched later in the recursive calls or it is
2540 // gone. Anyway, we must not fold it into the addressing mode at this point.
2541 // E.g.,
2542 // op = add opnd, 1
2543 // idx = ext op
2544 // addr = gep base, idx
2545 // is now:
2546 // promotedOpnd = ext opnd <- no match here
2547 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2548 // addr = gep base, op <- match
2549 if (MovedAway)
2550 *MovedAway = true;
2551
2552 assert(PromotedOperand &&
2553 "TypePromotionHelper should have filtered out those cases");
2554
2555 ExtAddrMode BackupAddrMode = AddrMode;
2556 unsigned OldSize = AddrModeInsts.size();
2557
2558 if (!MatchAddr(PromotedOperand, Depth) ||
2559 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2560 PromotedOperand)) {
2561 AddrMode = BackupAddrMode;
2562 AddrModeInsts.resize(OldSize);
2563 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2564 TPT.rollback(LastKnownGood);
2565 return false;
2566 }
2567 return true;
2568 }
2569 }
2570 return false;
2571 }
2572
2573 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2574 /// addressing mode. If Addr can't be added to AddrMode this returns false and
2575 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2576 /// or intptr_t for the target.
2577 ///
MatchAddr(Value * Addr,unsigned Depth)2578 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2579 // Start a transaction at this point that we will rollback if the matching
2580 // fails.
2581 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2582 TPT.getRestorationPoint();
2583 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2584 // Fold in immediates if legal for the target.
2585 AddrMode.BaseOffs += CI->getSExtValue();
2586 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2587 return true;
2588 AddrMode.BaseOffs -= CI->getSExtValue();
2589 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2590 // If this is a global variable, try to fold it into the addressing mode.
2591 if (!AddrMode.BaseGV) {
2592 AddrMode.BaseGV = GV;
2593 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2594 return true;
2595 AddrMode.BaseGV = nullptr;
2596 }
2597 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2598 ExtAddrMode BackupAddrMode = AddrMode;
2599 unsigned OldSize = AddrModeInsts.size();
2600
2601 // Check to see if it is possible to fold this operation.
2602 bool MovedAway = false;
2603 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2604 // This instruction may have been move away. If so, there is nothing
2605 // to check here.
2606 if (MovedAway)
2607 return true;
2608 // Okay, it's possible to fold this. Check to see if it is actually
2609 // *profitable* to do so. We use a simple cost model to avoid increasing
2610 // register pressure too much.
2611 if (I->hasOneUse() ||
2612 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2613 AddrModeInsts.push_back(I);
2614 return true;
2615 }
2616
2617 // It isn't profitable to do this, roll back.
2618 //cerr << "NOT FOLDING: " << *I;
2619 AddrMode = BackupAddrMode;
2620 AddrModeInsts.resize(OldSize);
2621 TPT.rollback(LastKnownGood);
2622 }
2623 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2624 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2625 return true;
2626 TPT.rollback(LastKnownGood);
2627 } else if (isa<ConstantPointerNull>(Addr)) {
2628 // Null pointer gets folded without affecting the addressing mode.
2629 return true;
2630 }
2631
2632 // Worse case, the target should support [reg] addressing modes. :)
2633 if (!AddrMode.HasBaseReg) {
2634 AddrMode.HasBaseReg = true;
2635 AddrMode.BaseReg = Addr;
2636 // Still check for legality in case the target supports [imm] but not [i+r].
2637 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2638 return true;
2639 AddrMode.HasBaseReg = false;
2640 AddrMode.BaseReg = nullptr;
2641 }
2642
2643 // If the base register is already taken, see if we can do [r+r].
2644 if (AddrMode.Scale == 0) {
2645 AddrMode.Scale = 1;
2646 AddrMode.ScaledReg = Addr;
2647 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2648 return true;
2649 AddrMode.Scale = 0;
2650 AddrMode.ScaledReg = nullptr;
2651 }
2652 // Couldn't match.
2653 TPT.rollback(LastKnownGood);
2654 return false;
2655 }
2656
2657 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2658 /// inline asm call are due to memory operands. If so, return true, otherwise
2659 /// return false.
IsOperandAMemoryOperand(CallInst * CI,InlineAsm * IA,Value * OpVal,const TargetLowering & TLI)2660 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2661 const TargetLowering &TLI) {
2662 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2663 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2664 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2665
2666 // Compute the constraint code and ConstraintType to use.
2667 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2668
2669 // If this asm operand is our Value*, and if it isn't an indirect memory
2670 // operand, we can't fold it!
2671 if (OpInfo.CallOperandVal == OpVal &&
2672 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2673 !OpInfo.isIndirect))
2674 return false;
2675 }
2676
2677 return true;
2678 }
2679
2680 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2681 /// memory use. If we find an obviously non-foldable instruction, return true.
2682 /// Add the ultimately found memory instructions to MemoryUses.
FindAllMemoryUses(Instruction * I,SmallVectorImpl<std::pair<Instruction *,unsigned>> & MemoryUses,SmallPtrSetImpl<Instruction * > & ConsideredInsts,const TargetLowering & TLI)2683 static bool FindAllMemoryUses(Instruction *I,
2684 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2685 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
2686 const TargetLowering &TLI) {
2687 // If we already considered this instruction, we're done.
2688 if (!ConsideredInsts.insert(I).second)
2689 return false;
2690
2691 // If this is an obviously unfoldable instruction, bail out.
2692 if (!MightBeFoldableInst(I))
2693 return true;
2694
2695 // Loop over all the uses, recursively processing them.
2696 for (Use &U : I->uses()) {
2697 Instruction *UserI = cast<Instruction>(U.getUser());
2698
2699 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2700 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2701 continue;
2702 }
2703
2704 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2705 unsigned opNo = U.getOperandNo();
2706 if (opNo == 0) return true; // Storing addr, not into addr.
2707 MemoryUses.push_back(std::make_pair(SI, opNo));
2708 continue;
2709 }
2710
2711 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2712 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2713 if (!IA) return true;
2714
2715 // If this is a memory operand, we're cool, otherwise bail out.
2716 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2717 return true;
2718 continue;
2719 }
2720
2721 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2722 return true;
2723 }
2724
2725 return false;
2726 }
2727
2728 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2729 /// the use site that we're folding it into. If so, there is no cost to
2730 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2731 /// that we know are live at the instruction already.
ValueAlreadyLiveAtInst(Value * Val,Value * KnownLive1,Value * KnownLive2)2732 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2733 Value *KnownLive2) {
2734 // If Val is either of the known-live values, we know it is live!
2735 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2736 return true;
2737
2738 // All values other than instructions and arguments (e.g. constants) are live.
2739 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2740
2741 // If Val is a constant sized alloca in the entry block, it is live, this is
2742 // true because it is just a reference to the stack/frame pointer, which is
2743 // live for the whole function.
2744 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2745 if (AI->isStaticAlloca())
2746 return true;
2747
2748 // Check to see if this value is already used in the memory instruction's
2749 // block. If so, it's already live into the block at the very least, so we
2750 // can reasonably fold it.
2751 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2752 }
2753
2754 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2755 /// mode of the machine to fold the specified instruction into a load or store
2756 /// that ultimately uses it. However, the specified instruction has multiple
2757 /// uses. Given this, it may actually increase register pressure to fold it
2758 /// into the load. For example, consider this code:
2759 ///
2760 /// X = ...
2761 /// Y = X+1
2762 /// use(Y) -> nonload/store
2763 /// Z = Y+1
2764 /// load Z
2765 ///
2766 /// In this case, Y has multiple uses, and can be folded into the load of Z
2767 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2768 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2769 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2770 /// number of computations either.
2771 ///
2772 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2773 /// X was live across 'load Z' for other reasons, we actually *would* want to
2774 /// fold the addressing mode in the Z case. This would make Y die earlier.
2775 bool AddressingModeMatcher::
IsProfitableToFoldIntoAddressingMode(Instruction * I,ExtAddrMode & AMBefore,ExtAddrMode & AMAfter)2776 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2777 ExtAddrMode &AMAfter) {
2778 if (IgnoreProfitability) return true;
2779
2780 // AMBefore is the addressing mode before this instruction was folded into it,
2781 // and AMAfter is the addressing mode after the instruction was folded. Get
2782 // the set of registers referenced by AMAfter and subtract out those
2783 // referenced by AMBefore: this is the set of values which folding in this
2784 // address extends the lifetime of.
2785 //
2786 // Note that there are only two potential values being referenced here,
2787 // BaseReg and ScaleReg (global addresses are always available, as are any
2788 // folded immediates).
2789 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2790
2791 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2792 // lifetime wasn't extended by adding this instruction.
2793 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2794 BaseReg = nullptr;
2795 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2796 ScaledReg = nullptr;
2797
2798 // If folding this instruction (and it's subexprs) didn't extend any live
2799 // ranges, we're ok with it.
2800 if (!BaseReg && !ScaledReg)
2801 return true;
2802
2803 // If all uses of this instruction are ultimately load/store/inlineasm's,
2804 // check to see if their addressing modes will include this instruction. If
2805 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2806 // uses.
2807 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2808 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2809 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2810 return false; // Has a non-memory, non-foldable use!
2811
2812 // Now that we know that all uses of this instruction are part of a chain of
2813 // computation involving only operations that could theoretically be folded
2814 // into a memory use, loop over each of these uses and see if they could
2815 // *actually* fold the instruction.
2816 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2817 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2818 Instruction *User = MemoryUses[i].first;
2819 unsigned OpNo = MemoryUses[i].second;
2820
2821 // Get the access type of this use. If the use isn't a pointer, we don't
2822 // know what it accesses.
2823 Value *Address = User->getOperand(OpNo);
2824 if (!Address->getType()->isPointerTy())
2825 return false;
2826 Type *AddressAccessTy = Address->getType()->getPointerElementType();
2827
2828 // Do a match against the root of this address, ignoring profitability. This
2829 // will tell us if the addressing mode for the memory operation will
2830 // *actually* cover the shared instruction.
2831 ExtAddrMode Result;
2832 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2833 TPT.getRestorationPoint();
2834 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2835 MemoryInst, Result, InsertedTruncs,
2836 PromotedInsts, TPT);
2837 Matcher.IgnoreProfitability = true;
2838 bool Success = Matcher.MatchAddr(Address, 0);
2839 (void)Success; assert(Success && "Couldn't select *anything*?");
2840
2841 // The match was to check the profitability, the changes made are not
2842 // part of the original matcher. Therefore, they should be dropped
2843 // otherwise the original matcher will not present the right state.
2844 TPT.rollback(LastKnownGood);
2845
2846 // If the match didn't cover I, then it won't be shared by it.
2847 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2848 I) == MatchedAddrModeInsts.end())
2849 return false;
2850
2851 MatchedAddrModeInsts.clear();
2852 }
2853
2854 return true;
2855 }
2856
2857 } // end anonymous namespace
2858
2859 /// IsNonLocalValue - Return true if the specified values are defined in a
2860 /// different basic block than BB.
IsNonLocalValue(Value * V,BasicBlock * BB)2861 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2862 if (Instruction *I = dyn_cast<Instruction>(V))
2863 return I->getParent() != BB;
2864 return false;
2865 }
2866
2867 /// OptimizeMemoryInst - Load and Store Instructions often have
2868 /// addressing modes that can do significant amounts of computation. As such,
2869 /// instruction selection will try to get the load or store to do as much
2870 /// computation as possible for the program. The problem is that isel can only
2871 /// see within a single block. As such, we sink as much legal addressing mode
2872 /// stuff into the block as possible.
2873 ///
2874 /// This method is used to optimize both load/store and inline asms with memory
2875 /// operands.
OptimizeMemoryInst(Instruction * MemoryInst,Value * Addr,Type * AccessTy)2876 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2877 Type *AccessTy) {
2878 Value *Repl = Addr;
2879
2880 // Try to collapse single-value PHI nodes. This is necessary to undo
2881 // unprofitable PRE transformations.
2882 SmallVector<Value*, 8> worklist;
2883 SmallPtrSet<Value*, 16> Visited;
2884 worklist.push_back(Addr);
2885
2886 // Use a worklist to iteratively look through PHI nodes, and ensure that
2887 // the addressing mode obtained from the non-PHI roots of the graph
2888 // are equivalent.
2889 Value *Consensus = nullptr;
2890 unsigned NumUsesConsensus = 0;
2891 bool IsNumUsesConsensusValid = false;
2892 SmallVector<Instruction*, 16> AddrModeInsts;
2893 ExtAddrMode AddrMode;
2894 TypePromotionTransaction TPT;
2895 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2896 TPT.getRestorationPoint();
2897 while (!worklist.empty()) {
2898 Value *V = worklist.back();
2899 worklist.pop_back();
2900
2901 // Break use-def graph loops.
2902 if (!Visited.insert(V).second) {
2903 Consensus = nullptr;
2904 break;
2905 }
2906
2907 // For a PHI node, push all of its incoming values.
2908 if (PHINode *P = dyn_cast<PHINode>(V)) {
2909 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2910 worklist.push_back(P->getIncomingValue(i));
2911 continue;
2912 }
2913
2914 // For non-PHIs, determine the addressing mode being computed.
2915 SmallVector<Instruction*, 16> NewAddrModeInsts;
2916 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2917 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2918 PromotedInsts, TPT);
2919
2920 // This check is broken into two cases with very similar code to avoid using
2921 // getNumUses() as much as possible. Some values have a lot of uses, so
2922 // calling getNumUses() unconditionally caused a significant compile-time
2923 // regression.
2924 if (!Consensus) {
2925 Consensus = V;
2926 AddrMode = NewAddrMode;
2927 AddrModeInsts = NewAddrModeInsts;
2928 continue;
2929 } else if (NewAddrMode == AddrMode) {
2930 if (!IsNumUsesConsensusValid) {
2931 NumUsesConsensus = Consensus->getNumUses();
2932 IsNumUsesConsensusValid = true;
2933 }
2934
2935 // Ensure that the obtained addressing mode is equivalent to that obtained
2936 // for all other roots of the PHI traversal. Also, when choosing one
2937 // such root as representative, select the one with the most uses in order
2938 // to keep the cost modeling heuristics in AddressingModeMatcher
2939 // applicable.
2940 unsigned NumUses = V->getNumUses();
2941 if (NumUses > NumUsesConsensus) {
2942 Consensus = V;
2943 NumUsesConsensus = NumUses;
2944 AddrModeInsts = NewAddrModeInsts;
2945 }
2946 continue;
2947 }
2948
2949 Consensus = nullptr;
2950 break;
2951 }
2952
2953 // If the addressing mode couldn't be determined, or if multiple different
2954 // ones were determined, bail out now.
2955 if (!Consensus) {
2956 TPT.rollback(LastKnownGood);
2957 return false;
2958 }
2959 TPT.commit();
2960
2961 // Check to see if any of the instructions supersumed by this addr mode are
2962 // non-local to I's BB.
2963 bool AnyNonLocal = false;
2964 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2965 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2966 AnyNonLocal = true;
2967 break;
2968 }
2969 }
2970
2971 // If all the instructions matched are already in this BB, don't do anything.
2972 if (!AnyNonLocal) {
2973 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
2974 return false;
2975 }
2976
2977 // Insert this computation right after this user. Since our caller is
2978 // scanning from the top of the BB to the bottom, reuse of the expr are
2979 // guaranteed to happen later.
2980 IRBuilder<> Builder(MemoryInst);
2981
2982 // Now that we determined the addressing expression we want to use and know
2983 // that we have to sink it into this block. Check to see if we have already
2984 // done this for some other load/store instr in this block. If so, reuse the
2985 // computation.
2986 Value *&SunkAddr = SunkAddrs[Addr];
2987 if (SunkAddr) {
2988 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2989 << *MemoryInst << "\n");
2990 if (SunkAddr->getType() != Addr->getType())
2991 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2992 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2993 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2994 // By default, we use the GEP-based method when AA is used later. This
2995 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2996 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2997 << *MemoryInst << "\n");
2998 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2999 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
3000
3001 // First, find the pointer.
3002 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3003 ResultPtr = AddrMode.BaseReg;
3004 AddrMode.BaseReg = nullptr;
3005 }
3006
3007 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3008 // We can't add more than one pointer together, nor can we scale a
3009 // pointer (both of which seem meaningless).
3010 if (ResultPtr || AddrMode.Scale != 1)
3011 return false;
3012
3013 ResultPtr = AddrMode.ScaledReg;
3014 AddrMode.Scale = 0;
3015 }
3016
3017 if (AddrMode.BaseGV) {
3018 if (ResultPtr)
3019 return false;
3020
3021 ResultPtr = AddrMode.BaseGV;
3022 }
3023
3024 // If the real base value actually came from an inttoptr, then the matcher
3025 // will look through it and provide only the integer value. In that case,
3026 // use it here.
3027 if (!ResultPtr && AddrMode.BaseReg) {
3028 ResultPtr =
3029 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
3030 AddrMode.BaseReg = nullptr;
3031 } else if (!ResultPtr && AddrMode.Scale == 1) {
3032 ResultPtr =
3033 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3034 AddrMode.Scale = 0;
3035 }
3036
3037 if (!ResultPtr &&
3038 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3039 SunkAddr = Constant::getNullValue(Addr->getType());
3040 } else if (!ResultPtr) {
3041 return false;
3042 } else {
3043 Type *I8PtrTy =
3044 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3045
3046 // Start with the base register. Do this first so that subsequent address
3047 // matching finds it last, which will prevent it from trying to match it
3048 // as the scaled value in case it happens to be a mul. That would be
3049 // problematic if we've sunk a different mul for the scale, because then
3050 // we'd end up sinking both muls.
3051 if (AddrMode.BaseReg) {
3052 Value *V = AddrMode.BaseReg;
3053 if (V->getType() != IntPtrTy)
3054 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3055
3056 ResultIndex = V;
3057 }
3058
3059 // Add the scale value.
3060 if (AddrMode.Scale) {
3061 Value *V = AddrMode.ScaledReg;
3062 if (V->getType() == IntPtrTy) {
3063 // done.
3064 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3065 cast<IntegerType>(V->getType())->getBitWidth()) {
3066 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3067 } else {
3068 // It is only safe to sign extend the BaseReg if we know that the math
3069 // required to create it did not overflow before we extend it. Since
3070 // the original IR value was tossed in favor of a constant back when
3071 // the AddrMode was created we need to bail out gracefully if widths
3072 // do not match instead of extending it.
3073 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3074 if (I && (ResultIndex != AddrMode.BaseReg))
3075 I->eraseFromParent();
3076 return false;
3077 }
3078
3079 if (AddrMode.Scale != 1)
3080 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3081 "sunkaddr");
3082 if (ResultIndex)
3083 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3084 else
3085 ResultIndex = V;
3086 }
3087
3088 // Add in the Base Offset if present.
3089 if (AddrMode.BaseOffs) {
3090 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3091 if (ResultIndex) {
3092 // We need to add this separately from the scale above to help with
3093 // SDAG consecutive load/store merging.
3094 if (ResultPtr->getType() != I8PtrTy)
3095 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3096 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3097 }
3098
3099 ResultIndex = V;
3100 }
3101
3102 if (!ResultIndex) {
3103 SunkAddr = ResultPtr;
3104 } else {
3105 if (ResultPtr->getType() != I8PtrTy)
3106 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3107 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3108 }
3109
3110 if (SunkAddr->getType() != Addr->getType())
3111 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3112 }
3113 } else {
3114 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3115 << *MemoryInst << "\n");
3116 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
3117 Value *Result = nullptr;
3118
3119 // Start with the base register. Do this first so that subsequent address
3120 // matching finds it last, which will prevent it from trying to match it
3121 // as the scaled value in case it happens to be a mul. That would be
3122 // problematic if we've sunk a different mul for the scale, because then
3123 // we'd end up sinking both muls.
3124 if (AddrMode.BaseReg) {
3125 Value *V = AddrMode.BaseReg;
3126 if (V->getType()->isPointerTy())
3127 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3128 if (V->getType() != IntPtrTy)
3129 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3130 Result = V;
3131 }
3132
3133 // Add the scale value.
3134 if (AddrMode.Scale) {
3135 Value *V = AddrMode.ScaledReg;
3136 if (V->getType() == IntPtrTy) {
3137 // done.
3138 } else if (V->getType()->isPointerTy()) {
3139 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3140 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3141 cast<IntegerType>(V->getType())->getBitWidth()) {
3142 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3143 } else {
3144 // It is only safe to sign extend the BaseReg if we know that the math
3145 // required to create it did not overflow before we extend it. Since
3146 // the original IR value was tossed in favor of a constant back when
3147 // the AddrMode was created we need to bail out gracefully if widths
3148 // do not match instead of extending it.
3149 Instruction *I = dyn_cast_or_null<Instruction>(Result);
3150 if (I && (Result != AddrMode.BaseReg))
3151 I->eraseFromParent();
3152 return false;
3153 }
3154 if (AddrMode.Scale != 1)
3155 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3156 "sunkaddr");
3157 if (Result)
3158 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3159 else
3160 Result = V;
3161 }
3162
3163 // Add in the BaseGV if present.
3164 if (AddrMode.BaseGV) {
3165 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
3166 if (Result)
3167 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3168 else
3169 Result = V;
3170 }
3171
3172 // Add in the Base Offset if present.
3173 if (AddrMode.BaseOffs) {
3174 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3175 if (Result)
3176 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3177 else
3178 Result = V;
3179 }
3180
3181 if (!Result)
3182 SunkAddr = Constant::getNullValue(Addr->getType());
3183 else
3184 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
3185 }
3186
3187 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
3188
3189 // If we have no uses, recursively delete the value and all dead instructions
3190 // using it.
3191 if (Repl->use_empty()) {
3192 // This can cause recursive deletion, which can invalidate our iterator.
3193 // Use a WeakVH to hold onto it in case this happens.
3194 WeakVH IterHandle(CurInstIterator);
3195 BasicBlock *BB = CurInstIterator->getParent();
3196
3197 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
3198
3199 if (IterHandle != CurInstIterator) {
3200 // If the iterator instruction was recursively deleted, start over at the
3201 // start of the block.
3202 CurInstIterator = BB->begin();
3203 SunkAddrs.clear();
3204 }
3205 }
3206 ++NumMemoryInsts;
3207 return true;
3208 }
3209
3210 /// OptimizeInlineAsmInst - If there are any memory operands, use
3211 /// OptimizeMemoryInst to sink their address computing into the block when
3212 /// possible / profitable.
OptimizeInlineAsmInst(CallInst * CS)3213 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
3214 bool MadeChange = false;
3215
3216 TargetLowering::AsmOperandInfoVector
3217 TargetConstraints = TLI->ParseConstraints(CS);
3218 unsigned ArgNo = 0;
3219 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3220 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3221
3222 // Compute the constraint code and ConstraintType to use.
3223 TLI->ComputeConstraintToUse(OpInfo, SDValue());
3224
3225 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3226 OpInfo.isIndirect) {
3227 Value *OpVal = CS->getArgOperand(ArgNo++);
3228 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
3229 } else if (OpInfo.Type == InlineAsm::isInput)
3230 ArgNo++;
3231 }
3232
3233 return MadeChange;
3234 }
3235
3236 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3237 /// sign extensions.
hasSameExtUse(Instruction * Inst,const TargetLowering & TLI)3238 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3239 assert(!Inst->use_empty() && "Input must have at least one use");
3240 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3241 bool IsSExt = isa<SExtInst>(FirstUser);
3242 Type *ExtTy = FirstUser->getType();
3243 for (const User *U : Inst->users()) {
3244 const Instruction *UI = cast<Instruction>(U);
3245 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3246 return false;
3247 Type *CurTy = UI->getType();
3248 // Same input and output types: Same instruction after CSE.
3249 if (CurTy == ExtTy)
3250 continue;
3251
3252 // If IsSExt is true, we are in this situation:
3253 // a = Inst
3254 // b = sext ty1 a to ty2
3255 // c = sext ty1 a to ty3
3256 // Assuming ty2 is shorter than ty3, this could be turned into:
3257 // a = Inst
3258 // b = sext ty1 a to ty2
3259 // c = sext ty2 b to ty3
3260 // However, the last sext is not free.
3261 if (IsSExt)
3262 return false;
3263
3264 // This is a ZExt, maybe this is free to extend from one type to another.
3265 // In that case, we would not account for a different use.
3266 Type *NarrowTy;
3267 Type *LargeTy;
3268 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3269 CurTy->getScalarType()->getIntegerBitWidth()) {
3270 NarrowTy = CurTy;
3271 LargeTy = ExtTy;
3272 } else {
3273 NarrowTy = ExtTy;
3274 LargeTy = CurTy;
3275 }
3276
3277 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3278 return false;
3279 }
3280 // All uses are the same or can be derived from one another for free.
3281 return true;
3282 }
3283
3284 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
3285 /// load instruction.
3286 /// If an ext(load) can be formed, it is returned via \p LI for the load
3287 /// and \p Inst for the extension.
3288 /// Otherwise LI == nullptr and Inst == nullptr.
3289 /// When some promotion happened, \p TPT contains the proper state to
3290 /// revert them.
3291 ///
3292 /// \return true when promoting was necessary to expose the ext(load)
3293 /// opportunity, false otherwise.
3294 ///
3295 /// Example:
3296 /// \code
3297 /// %ld = load i32* %addr
3298 /// %add = add nuw i32 %ld, 4
3299 /// %zext = zext i32 %add to i64
3300 /// \endcode
3301 /// =>
3302 /// \code
3303 /// %ld = load i32* %addr
3304 /// %zext = zext i32 %ld to i64
3305 /// %add = add nuw i64 %zext, 4
3306 /// \encode
3307 /// Thanks to the promotion, we can match zext(load i32*) to i64.
ExtLdPromotion(TypePromotionTransaction & TPT,LoadInst * & LI,Instruction * & Inst,const SmallVectorImpl<Instruction * > & Exts,unsigned CreatedInsts=0)3308 bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3309 LoadInst *&LI, Instruction *&Inst,
3310 const SmallVectorImpl<Instruction *> &Exts,
3311 unsigned CreatedInsts = 0) {
3312 // Iterate over all the extensions to see if one form an ext(load).
3313 for (auto I : Exts) {
3314 // Check if we directly have ext(load).
3315 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3316 Inst = I;
3317 // No promotion happened here.
3318 return false;
3319 }
3320 // Check whether or not we want to do any promotion.
3321 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3322 continue;
3323 // Get the action to perform the promotion.
3324 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3325 I, InsertedTruncsSet, *TLI, PromotedInsts);
3326 // Check if we can promote.
3327 if (!TPH)
3328 continue;
3329 // Save the current state.
3330 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3331 TPT.getRestorationPoint();
3332 SmallVector<Instruction *, 4> NewExts;
3333 unsigned NewCreatedInsts = 0;
3334 // Promote.
3335 Value *PromotedVal =
3336 TPH(I, TPT, PromotedInsts, NewCreatedInsts, &NewExts, nullptr);
3337 assert(PromotedVal &&
3338 "TypePromotionHelper should have filtered out those cases");
3339
3340 // We would be able to merge only one extension in a load.
3341 // Therefore, if we have more than 1 new extension we heuristically
3342 // cut this search path, because it means we degrade the code quality.
3343 // With exactly 2, the transformation is neutral, because we will merge
3344 // one extension but leave one. However, we optimistically keep going,
3345 // because the new extension may be removed too.
3346 unsigned TotalCreatedInsts = CreatedInsts + NewCreatedInsts;
3347 if (!StressExtLdPromotion &&
3348 (TotalCreatedInsts > 1 ||
3349 !isPromotedInstructionLegal(*TLI, PromotedVal))) {
3350 // The promotion is not profitable, rollback to the previous state.
3351 TPT.rollback(LastKnownGood);
3352 continue;
3353 }
3354 // The promotion is profitable.
3355 // Check if it exposes an ext(load).
3356 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInsts);
3357 if (LI && (StressExtLdPromotion || NewCreatedInsts == 0 ||
3358 // If we have created a new extension, i.e., now we have two
3359 // extensions. We must make sure one of them is merged with
3360 // the load, otherwise we may degrade the code quality.
3361 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3362 // Promotion happened.
3363 return true;
3364 // If this does not help to expose an ext(load) then, rollback.
3365 TPT.rollback(LastKnownGood);
3366 }
3367 // None of the extension can form an ext(load).
3368 LI = nullptr;
3369 Inst = nullptr;
3370 return false;
3371 }
3372
3373 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3374 /// basic block as the load, unless conditions are unfavorable. This allows
3375 /// SelectionDAG to fold the extend into the load.
3376 /// \p I[in/out] the extension may be modified during the process if some
3377 /// promotions apply.
3378 ///
MoveExtToFormExtLoad(Instruction * & I)3379 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3380 // Try to promote a chain of computation if it allows to form
3381 // an extended load.
3382 TypePromotionTransaction TPT;
3383 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3384 TPT.getRestorationPoint();
3385 SmallVector<Instruction *, 1> Exts;
3386 Exts.push_back(I);
3387 // Look for a load being extended.
3388 LoadInst *LI = nullptr;
3389 Instruction *OldExt = I;
3390 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3391 if (!LI || !I) {
3392 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3393 "the code must remain the same");
3394 I = OldExt;
3395 return false;
3396 }
3397
3398 // If they're already in the same block, there's nothing to do.
3399 // Make the cheap checks first if we did not promote.
3400 // If we promoted, we need to check if it is indeed profitable.
3401 if (!HasPromoted && LI->getParent() == I->getParent())
3402 return false;
3403
3404 EVT VT = TLI->getValueType(I->getType());
3405 EVT LoadVT = TLI->getValueType(LI->getType());
3406
3407 // If the load has other users and the truncate is not free, this probably
3408 // isn't worthwhile.
3409 if (!LI->hasOneUse() && TLI &&
3410 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
3411 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3412 I = OldExt;
3413 TPT.rollback(LastKnownGood);
3414 return false;
3415 }
3416
3417 // Check whether the target supports casts folded into loads.
3418 unsigned LType;
3419 if (isa<ZExtInst>(I))
3420 LType = ISD::ZEXTLOAD;
3421 else {
3422 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3423 LType = ISD::SEXTLOAD;
3424 }
3425 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
3426 I = OldExt;
3427 TPT.rollback(LastKnownGood);
3428 return false;
3429 }
3430
3431 // Move the extend into the same block as the load, so that SelectionDAG
3432 // can fold it.
3433 TPT.commit();
3434 I->removeFromParent();
3435 I->insertAfter(LI);
3436 ++NumExtsMoved;
3437 return true;
3438 }
3439
OptimizeExtUses(Instruction * I)3440 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3441 BasicBlock *DefBB = I->getParent();
3442
3443 // If the result of a {s|z}ext and its source are both live out, rewrite all
3444 // other uses of the source with result of extension.
3445 Value *Src = I->getOperand(0);
3446 if (Src->hasOneUse())
3447 return false;
3448
3449 // Only do this xform if truncating is free.
3450 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
3451 return false;
3452
3453 // Only safe to perform the optimization if the source is also defined in
3454 // this block.
3455 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
3456 return false;
3457
3458 bool DefIsLiveOut = false;
3459 for (User *U : I->users()) {
3460 Instruction *UI = cast<Instruction>(U);
3461
3462 // Figure out which BB this ext is used in.
3463 BasicBlock *UserBB = UI->getParent();
3464 if (UserBB == DefBB) continue;
3465 DefIsLiveOut = true;
3466 break;
3467 }
3468 if (!DefIsLiveOut)
3469 return false;
3470
3471 // Make sure none of the uses are PHI nodes.
3472 for (User *U : Src->users()) {
3473 Instruction *UI = cast<Instruction>(U);
3474 BasicBlock *UserBB = UI->getParent();
3475 if (UserBB == DefBB) continue;
3476 // Be conservative. We don't want this xform to end up introducing
3477 // reloads just before load / store instructions.
3478 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
3479 return false;
3480 }
3481
3482 // InsertedTruncs - Only insert one trunc in each block once.
3483 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3484
3485 bool MadeChange = false;
3486 for (Use &U : Src->uses()) {
3487 Instruction *User = cast<Instruction>(U.getUser());
3488
3489 // Figure out which BB this ext is used in.
3490 BasicBlock *UserBB = User->getParent();
3491 if (UserBB == DefBB) continue;
3492
3493 // Both src and def are live in this block. Rewrite the use.
3494 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3495
3496 if (!InsertedTrunc) {
3497 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3498 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3499 InsertedTruncsSet.insert(InsertedTrunc);
3500 }
3501
3502 // Replace a use of the {s|z}ext source with a use of the result.
3503 U = InsertedTrunc;
3504 ++NumExtUses;
3505 MadeChange = true;
3506 }
3507
3508 return MadeChange;
3509 }
3510
3511 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3512 /// turned into an explicit branch.
isFormingBranchFromSelectProfitable(SelectInst * SI)3513 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3514 // FIXME: This should use the same heuristics as IfConversion to determine
3515 // whether a select is better represented as a branch. This requires that
3516 // branch probability metadata is preserved for the select, which is not the
3517 // case currently.
3518
3519 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3520
3521 // If the branch is predicted right, an out of order CPU can avoid blocking on
3522 // the compare. Emit cmovs on compares with a memory operand as branches to
3523 // avoid stalls on the load from memory. If the compare has more than one use
3524 // there's probably another cmov or setcc around so it's not worth emitting a
3525 // branch.
3526 if (!Cmp)
3527 return false;
3528
3529 Value *CmpOp0 = Cmp->getOperand(0);
3530 Value *CmpOp1 = Cmp->getOperand(1);
3531
3532 // We check that the memory operand has one use to avoid uses of the loaded
3533 // value directly after the compare, making branches unprofitable.
3534 return Cmp->hasOneUse() &&
3535 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3536 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3537 }
3538
3539
3540 /// If we have a SelectInst that will likely profit from branch prediction,
3541 /// turn it into a branch.
OptimizeSelectInst(SelectInst * SI)3542 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3543 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3544
3545 // Can we convert the 'select' to CF ?
3546 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3547 return false;
3548
3549 TargetLowering::SelectSupportKind SelectKind;
3550 if (VectorCond)
3551 SelectKind = TargetLowering::VectorMaskSelect;
3552 else if (SI->getType()->isVectorTy())
3553 SelectKind = TargetLowering::ScalarCondVectorVal;
3554 else
3555 SelectKind = TargetLowering::ScalarValSelect;
3556
3557 // Do we have efficient codegen support for this kind of 'selects' ?
3558 if (TLI->isSelectSupported(SelectKind)) {
3559 // We have efficient codegen support for the select instruction.
3560 // Check if it is profitable to keep this 'select'.
3561 if (!TLI->isPredictableSelectExpensive() ||
3562 !isFormingBranchFromSelectProfitable(SI))
3563 return false;
3564 }
3565
3566 ModifiedDT = true;
3567
3568 // First, we split the block containing the select into 2 blocks.
3569 BasicBlock *StartBlock = SI->getParent();
3570 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3571 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3572
3573 // Create a new block serving as the landing pad for the branch.
3574 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3575 NextBlock->getParent(), NextBlock);
3576
3577 // Move the unconditional branch from the block with the select in it into our
3578 // landing pad block.
3579 StartBlock->getTerminator()->eraseFromParent();
3580 BranchInst::Create(NextBlock, SmallBlock);
3581
3582 // Insert the real conditional branch based on the original condition.
3583 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3584
3585 // The select itself is replaced with a PHI Node.
3586 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3587 PN->takeName(SI);
3588 PN->addIncoming(SI->getTrueValue(), StartBlock);
3589 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3590 SI->replaceAllUsesWith(PN);
3591 SI->eraseFromParent();
3592
3593 // Instruct OptimizeBlock to skip to the next block.
3594 CurInstIterator = StartBlock->end();
3595 ++NumSelectsExpanded;
3596 return true;
3597 }
3598
isBroadcastShuffle(ShuffleVectorInst * SVI)3599 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3600 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3601 int SplatElem = -1;
3602 for (unsigned i = 0; i < Mask.size(); ++i) {
3603 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3604 return false;
3605 SplatElem = Mask[i];
3606 }
3607
3608 return true;
3609 }
3610
3611 /// Some targets have expensive vector shifts if the lanes aren't all the same
3612 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3613 /// it's often worth sinking a shufflevector splat down to its use so that
3614 /// codegen can spot all lanes are identical.
OptimizeShuffleVectorInst(ShuffleVectorInst * SVI)3615 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3616 BasicBlock *DefBB = SVI->getParent();
3617
3618 // Only do this xform if variable vector shifts are particularly expensive.
3619 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3620 return false;
3621
3622 // We only expect better codegen by sinking a shuffle if we can recognise a
3623 // constant splat.
3624 if (!isBroadcastShuffle(SVI))
3625 return false;
3626
3627 // InsertedShuffles - Only insert a shuffle in each block once.
3628 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3629
3630 bool MadeChange = false;
3631 for (User *U : SVI->users()) {
3632 Instruction *UI = cast<Instruction>(U);
3633
3634 // Figure out which BB this ext is used in.
3635 BasicBlock *UserBB = UI->getParent();
3636 if (UserBB == DefBB) continue;
3637
3638 // For now only apply this when the splat is used by a shift instruction.
3639 if (!UI->isShift()) continue;
3640
3641 // Everything checks out, sink the shuffle if the user's block doesn't
3642 // already have a copy.
3643 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3644
3645 if (!InsertedShuffle) {
3646 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3647 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3648 SVI->getOperand(1),
3649 SVI->getOperand(2), "", InsertPt);
3650 }
3651
3652 UI->replaceUsesOfWith(SVI, InsertedShuffle);
3653 MadeChange = true;
3654 }
3655
3656 // If we removed all uses, nuke the shuffle.
3657 if (SVI->use_empty()) {
3658 SVI->eraseFromParent();
3659 MadeChange = true;
3660 }
3661
3662 return MadeChange;
3663 }
3664
3665 namespace {
3666 /// \brief Helper class to promote a scalar operation to a vector one.
3667 /// This class is used to move downward extractelement transition.
3668 /// E.g.,
3669 /// a = vector_op <2 x i32>
3670 /// b = extractelement <2 x i32> a, i32 0
3671 /// c = scalar_op b
3672 /// store c
3673 ///
3674 /// =>
3675 /// a = vector_op <2 x i32>
3676 /// c = vector_op a (equivalent to scalar_op on the related lane)
3677 /// * d = extractelement <2 x i32> c, i32 0
3678 /// * store d
3679 /// Assuming both extractelement and store can be combine, we get rid of the
3680 /// transition.
3681 class VectorPromoteHelper {
3682 /// Used to perform some checks on the legality of vector operations.
3683 const TargetLowering &TLI;
3684
3685 /// Used to estimated the cost of the promoted chain.
3686 const TargetTransformInfo &TTI;
3687
3688 /// The transition being moved downwards.
3689 Instruction *Transition;
3690 /// The sequence of instructions to be promoted.
3691 SmallVector<Instruction *, 4> InstsToBePromoted;
3692 /// Cost of combining a store and an extract.
3693 unsigned StoreExtractCombineCost;
3694 /// Instruction that will be combined with the transition.
3695 Instruction *CombineInst;
3696
3697 /// \brief The instruction that represents the current end of the transition.
3698 /// Since we are faking the promotion until we reach the end of the chain
3699 /// of computation, we need a way to get the current end of the transition.
getEndOfTransition() const3700 Instruction *getEndOfTransition() const {
3701 if (InstsToBePromoted.empty())
3702 return Transition;
3703 return InstsToBePromoted.back();
3704 }
3705
3706 /// \brief Return the index of the original value in the transition.
3707 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3708 /// c, is at index 0.
getTransitionOriginalValueIdx() const3709 unsigned getTransitionOriginalValueIdx() const {
3710 assert(isa<ExtractElementInst>(Transition) &&
3711 "Other kind of transitions are not supported yet");
3712 return 0;
3713 }
3714
3715 /// \brief Return the index of the index in the transition.
3716 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3717 /// is at index 1.
getTransitionIdx() const3718 unsigned getTransitionIdx() const {
3719 assert(isa<ExtractElementInst>(Transition) &&
3720 "Other kind of transitions are not supported yet");
3721 return 1;
3722 }
3723
3724 /// \brief Get the type of the transition.
3725 /// This is the type of the original value.
3726 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3727 /// transition is <2 x i32>.
getTransitionType() const3728 Type *getTransitionType() const {
3729 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3730 }
3731
3732 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3733 /// I.e., we have the following sequence:
3734 /// Def = Transition <ty1> a to <ty2>
3735 /// b = ToBePromoted <ty2> Def, ...
3736 /// =>
3737 /// b = ToBePromoted <ty1> a, ...
3738 /// Def = Transition <ty1> ToBePromoted to <ty2>
3739 void promoteImpl(Instruction *ToBePromoted);
3740
3741 /// \brief Check whether or not it is profitable to promote all the
3742 /// instructions enqueued to be promoted.
isProfitableToPromote()3743 bool isProfitableToPromote() {
3744 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3745 unsigned Index = isa<ConstantInt>(ValIdx)
3746 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3747 : -1;
3748 Type *PromotedType = getTransitionType();
3749
3750 StoreInst *ST = cast<StoreInst>(CombineInst);
3751 unsigned AS = ST->getPointerAddressSpace();
3752 unsigned Align = ST->getAlignment();
3753 // Check if this store is supported.
3754 if (!TLI.allowsMisalignedMemoryAccesses(
3755 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
3756 // If this is not supported, there is no way we can combine
3757 // the extract with the store.
3758 return false;
3759 }
3760
3761 // The scalar chain of computation has to pay for the transition
3762 // scalar to vector.
3763 // The vector chain has to account for the combining cost.
3764 uint64_t ScalarCost =
3765 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3766 uint64_t VectorCost = StoreExtractCombineCost;
3767 for (const auto &Inst : InstsToBePromoted) {
3768 // Compute the cost.
3769 // By construction, all instructions being promoted are arithmetic ones.
3770 // Moreover, one argument is a constant that can be viewed as a splat
3771 // constant.
3772 Value *Arg0 = Inst->getOperand(0);
3773 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3774 isa<ConstantFP>(Arg0);
3775 TargetTransformInfo::OperandValueKind Arg0OVK =
3776 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3777 : TargetTransformInfo::OK_AnyValue;
3778 TargetTransformInfo::OperandValueKind Arg1OVK =
3779 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3780 : TargetTransformInfo::OK_AnyValue;
3781 ScalarCost += TTI.getArithmeticInstrCost(
3782 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3783 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3784 Arg0OVK, Arg1OVK);
3785 }
3786 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3787 << ScalarCost << "\nVector: " << VectorCost << '\n');
3788 return ScalarCost > VectorCost;
3789 }
3790
3791 /// \brief Generate a constant vector with \p Val with the same
3792 /// number of elements as the transition.
3793 /// \p UseSplat defines whether or not \p Val should be replicated
3794 /// accross the whole vector.
3795 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3796 /// otherwise we generate a vector with as many undef as possible:
3797 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3798 /// used at the index of the extract.
getConstantVector(Constant * Val,bool UseSplat) const3799 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3800 unsigned ExtractIdx = UINT_MAX;
3801 if (!UseSplat) {
3802 // If we cannot determine where the constant must be, we have to
3803 // use a splat constant.
3804 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3805 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3806 ExtractIdx = CstVal->getSExtValue();
3807 else
3808 UseSplat = true;
3809 }
3810
3811 unsigned End = getTransitionType()->getVectorNumElements();
3812 if (UseSplat)
3813 return ConstantVector::getSplat(End, Val);
3814
3815 SmallVector<Constant *, 4> ConstVec;
3816 UndefValue *UndefVal = UndefValue::get(Val->getType());
3817 for (unsigned Idx = 0; Idx != End; ++Idx) {
3818 if (Idx == ExtractIdx)
3819 ConstVec.push_back(Val);
3820 else
3821 ConstVec.push_back(UndefVal);
3822 }
3823 return ConstantVector::get(ConstVec);
3824 }
3825
3826 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3827 /// in \p Use can trigger undefined behavior.
canCauseUndefinedBehavior(const Instruction * Use,unsigned OperandIdx)3828 static bool canCauseUndefinedBehavior(const Instruction *Use,
3829 unsigned OperandIdx) {
3830 // This is not safe to introduce undef when the operand is on
3831 // the right hand side of a division-like instruction.
3832 if (OperandIdx != 1)
3833 return false;
3834 switch (Use->getOpcode()) {
3835 default:
3836 return false;
3837 case Instruction::SDiv:
3838 case Instruction::UDiv:
3839 case Instruction::SRem:
3840 case Instruction::URem:
3841 return true;
3842 case Instruction::FDiv:
3843 case Instruction::FRem:
3844 return !Use->hasNoNaNs();
3845 }
3846 llvm_unreachable(nullptr);
3847 }
3848
3849 public:
VectorPromoteHelper(const TargetLowering & TLI,const TargetTransformInfo & TTI,Instruction * Transition,unsigned CombineCost)3850 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3851 Instruction *Transition, unsigned CombineCost)
3852 : TLI(TLI), TTI(TTI), Transition(Transition),
3853 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3854 assert(Transition && "Do not know how to promote null");
3855 }
3856
3857 /// \brief Check if we can promote \p ToBePromoted to \p Type.
canPromote(const Instruction * ToBePromoted) const3858 bool canPromote(const Instruction *ToBePromoted) const {
3859 // We could support CastInst too.
3860 return isa<BinaryOperator>(ToBePromoted);
3861 }
3862
3863 /// \brief Check if it is profitable to promote \p ToBePromoted
3864 /// by moving downward the transition through.
shouldPromote(const Instruction * ToBePromoted) const3865 bool shouldPromote(const Instruction *ToBePromoted) const {
3866 // Promote only if all the operands can be statically expanded.
3867 // Indeed, we do not want to introduce any new kind of transitions.
3868 for (const Use &U : ToBePromoted->operands()) {
3869 const Value *Val = U.get();
3870 if (Val == getEndOfTransition()) {
3871 // If the use is a division and the transition is on the rhs,
3872 // we cannot promote the operation, otherwise we may create a
3873 // division by zero.
3874 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3875 return false;
3876 continue;
3877 }
3878 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3879 !isa<ConstantFP>(Val))
3880 return false;
3881 }
3882 // Check that the resulting operation is legal.
3883 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3884 if (!ISDOpcode)
3885 return false;
3886 return StressStoreExtract ||
3887 TLI.isOperationLegalOrCustom(
3888 ISDOpcode, TLI.getValueType(getTransitionType(), true));
3889 }
3890
3891 /// \brief Check whether or not \p Use can be combined
3892 /// with the transition.
3893 /// I.e., is it possible to do Use(Transition) => AnotherUse?
canCombine(const Instruction * Use)3894 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3895
3896 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
enqueueForPromotion(Instruction * ToBePromoted)3897 void enqueueForPromotion(Instruction *ToBePromoted) {
3898 InstsToBePromoted.push_back(ToBePromoted);
3899 }
3900
3901 /// \brief Set the instruction that will be combined with the transition.
recordCombineInstruction(Instruction * ToBeCombined)3902 void recordCombineInstruction(Instruction *ToBeCombined) {
3903 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3904 CombineInst = ToBeCombined;
3905 }
3906
3907 /// \brief Promote all the instructions enqueued for promotion if it is
3908 /// is profitable.
3909 /// \return True if the promotion happened, false otherwise.
promote()3910 bool promote() {
3911 // Check if there is something to promote.
3912 // Right now, if we do not have anything to combine with,
3913 // we assume the promotion is not profitable.
3914 if (InstsToBePromoted.empty() || !CombineInst)
3915 return false;
3916
3917 // Check cost.
3918 if (!StressStoreExtract && !isProfitableToPromote())
3919 return false;
3920
3921 // Promote.
3922 for (auto &ToBePromoted : InstsToBePromoted)
3923 promoteImpl(ToBePromoted);
3924 InstsToBePromoted.clear();
3925 return true;
3926 }
3927 };
3928 } // End of anonymous namespace.
3929
promoteImpl(Instruction * ToBePromoted)3930 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3931 // At this point, we know that all the operands of ToBePromoted but Def
3932 // can be statically promoted.
3933 // For Def, we need to use its parameter in ToBePromoted:
3934 // b = ToBePromoted ty1 a
3935 // Def = Transition ty1 b to ty2
3936 // Move the transition down.
3937 // 1. Replace all uses of the promoted operation by the transition.
3938 // = ... b => = ... Def.
3939 assert(ToBePromoted->getType() == Transition->getType() &&
3940 "The type of the result of the transition does not match "
3941 "the final type");
3942 ToBePromoted->replaceAllUsesWith(Transition);
3943 // 2. Update the type of the uses.
3944 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3945 Type *TransitionTy = getTransitionType();
3946 ToBePromoted->mutateType(TransitionTy);
3947 // 3. Update all the operands of the promoted operation with promoted
3948 // operands.
3949 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3950 for (Use &U : ToBePromoted->operands()) {
3951 Value *Val = U.get();
3952 Value *NewVal = nullptr;
3953 if (Val == Transition)
3954 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3955 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3956 isa<ConstantFP>(Val)) {
3957 // Use a splat constant if it is not safe to use undef.
3958 NewVal = getConstantVector(
3959 cast<Constant>(Val),
3960 isa<UndefValue>(Val) ||
3961 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3962 } else
3963 llvm_unreachable("Did you modified shouldPromote and forgot to update "
3964 "this?");
3965 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3966 }
3967 Transition->removeFromParent();
3968 Transition->insertAfter(ToBePromoted);
3969 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3970 }
3971
3972 // See if we can speculate calls to intrinsic cttz/ctlz.
3973 //
3974 // Example:
3975 // entry:
3976 // ...
3977 // %cmp = icmp eq i64 %val, 0
3978 // br i1 %cmp, label %end.bb, label %then.bb
3979 //
3980 // then.bb:
3981 // %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 true)
3982 // br label %EndBB
3983 //
3984 // end.bb:
3985 // %cond = phi i64 [ %c, %then.bb ], [ 64, %entry ]
3986 //
3987 // ==>
3988 //
3989 // entry:
3990 // ...
3991 // %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 false)
3992 //
OptimizeBranchInst(BranchInst * BrInst,const TargetLowering & TLI)3993 static bool OptimizeBranchInst(BranchInst *BrInst, const TargetLowering &TLI) {
3994 assert(BrInst->isConditional() && "Expected a conditional branch!");
3995 BasicBlock *ThenBB = BrInst->getSuccessor(1);
3996 BasicBlock *EndBB = BrInst->getSuccessor(0);
3997
3998 // See if ThenBB contains only one instruction (excluding the
3999 // terminator and DbgInfoIntrinsic calls).
4000 IntrinsicInst *II = nullptr;
4001 CastInst *CI = nullptr;
4002 for (BasicBlock::iterator I = ThenBB->begin(),
4003 E = std::prev(ThenBB->end()); I != E; ++I) {
4004 // Skip debug info.
4005 if (isa<DbgInfoIntrinsic>(I))
4006 continue;
4007
4008 // Check if this is a zero extension or a truncate of a previously
4009 // matched call to intrinsic cttz/ctlz.
4010 if (II) {
4011 // Early exit if we already found a "free" zero extend/truncate.
4012 if (CI)
4013 return false;
4014
4015 Type *SrcTy = II->getType();
4016 Type *DestTy = I->getType();
4017 Value *V;
4018
4019 if (match(cast<Instruction>(I), m_ZExt(m_Value(V))) && V == II) {
4020 // Speculate this zero extend only if it is "free" for the target.
4021 if (TLI.isZExtFree(SrcTy, DestTy)) {
4022 CI = cast<CastInst>(I);
4023 continue;
4024 }
4025 } else if (match(cast<Instruction>(I), m_Trunc(m_Value(V))) && V == II) {
4026 // Speculate this truncate only if it is "free" for the target.
4027 if (TLI.isTruncateFree(SrcTy, DestTy)) {
4028 CI = cast<CastInst>(I);
4029 continue;
4030 }
4031 } else {
4032 // Avoid speculating more than one instruction.
4033 return false;
4034 }
4035 }
4036
4037 // See if this is a call to intrinsic cttz/ctlz.
4038 if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::cttz>())) {
4039 // Avoid speculating expensive intrinsic calls.
4040 if (!TLI.isCheapToSpeculateCttz())
4041 return false;
4042 }
4043 else if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::ctlz>())) {
4044 // Avoid speculating expensive intrinsic calls.
4045 if (!TLI.isCheapToSpeculateCtlz())
4046 return false;
4047 } else
4048 return false;
4049
4050 II = cast<IntrinsicInst>(I);
4051 }
4052
4053 // Look for PHI nodes with 'II' as the incoming value from 'ThenBB'.
4054 BasicBlock *EntryBB = BrInst->getParent();
4055 for (BasicBlock::iterator I = EndBB->begin();
4056 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
4057 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
4058 Value *OrigV = PN->getIncomingValueForBlock(EntryBB);
4059
4060 if (!OrigV)
4061 return false;
4062
4063 if (ThenV != II && (!CI || ThenV != CI))
4064 return false;
4065
4066 if (ConstantInt *CInt = dyn_cast<ConstantInt>(OrigV)) {
4067 unsigned BitWidth = II->getType()->getIntegerBitWidth();
4068
4069 // Don't try to simplify this phi node if 'ThenV' is a cttz/ctlz
4070 // intrinsic call, but 'OrigV' is not equal to the 'size-of' in bits
4071 // of the value in input to the cttz/ctlz.
4072 if (CInt->getValue() != BitWidth)
4073 return false;
4074
4075 // Hoist the call to cttz/ctlz from ThenBB into EntryBB.
4076 EntryBB->getInstList().splice(BrInst, ThenBB->getInstList(),
4077 ThenBB->begin(), std::prev(ThenBB->end()));
4078
4079 // Update PN setting ThenV as the incoming value from both 'EntryBB'
4080 // and 'ThenBB'. Eventually, method 'OptimizeInst' will fold this
4081 // phi node if all the incoming values are the same.
4082 PN->setIncomingValue(PN->getBasicBlockIndex(EntryBB), ThenV);
4083 PN->setIncomingValue(PN->getBasicBlockIndex(ThenBB), ThenV);
4084
4085 // Clear the 'undef on zero' flag of the cttz/ctlz intrinsic call.
4086 if (cast<ConstantInt>(II->getArgOperand(1))->isOne()) {
4087 Type *Ty = II->getArgOperand(0)->getType();
4088 Value *Args[] = { II->getArgOperand(0),
4089 ConstantInt::getFalse(II->getContext()) };
4090 Module *M = EntryBB->getParent()->getParent();
4091 Value *IF = Intrinsic::getDeclaration(M, II->getIntrinsicID(), Ty);
4092 IRBuilder<> Builder(II);
4093 Instruction *NewI = Builder.CreateCall(IF, Args);
4094
4095 // Replace the old call to cttz/ctlz.
4096 II->replaceAllUsesWith(NewI);
4097 II->eraseFromParent();
4098 }
4099
4100 // Update BrInst condition so that the branch to EndBB is always taken.
4101 // Later on, method 'ConstantFoldTerminator' will simplify this branch
4102 // replacing it with a direct branch to 'EndBB'.
4103 // As a side effect, CodeGenPrepare will attempt to simplify the control
4104 // flow graph by deleting basic block 'ThenBB' and merging 'EntryBB' into
4105 // 'EndBB' (calling method 'EliminateFallThrough').
4106 BrInst->setCondition(ConstantInt::getTrue(BrInst->getContext()));
4107 return true;
4108 }
4109 }
4110
4111 return false;
4112 }
4113
4114 /// Some targets can do store(extractelement) with one instruction.
4115 /// Try to push the extractelement towards the stores when the target
4116 /// has this feature and this is profitable.
OptimizeExtractElementInst(Instruction * Inst)4117 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4118 unsigned CombineCost = UINT_MAX;
4119 if (DisableStoreExtract || !TLI ||
4120 (!StressStoreExtract &&
4121 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4122 Inst->getOperand(1), CombineCost)))
4123 return false;
4124
4125 // At this point we know that Inst is a vector to scalar transition.
4126 // Try to move it down the def-use chain, until:
4127 // - We can combine the transition with its single use
4128 // => we got rid of the transition.
4129 // - We escape the current basic block
4130 // => we would need to check that we are moving it at a cheaper place and
4131 // we do not do that for now.
4132 BasicBlock *Parent = Inst->getParent();
4133 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4134 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
4135 // If the transition has more than one use, assume this is not going to be
4136 // beneficial.
4137 while (Inst->hasOneUse()) {
4138 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4139 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4140
4141 if (ToBePromoted->getParent() != Parent) {
4142 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4143 << ToBePromoted->getParent()->getName()
4144 << ") than the transition (" << Parent->getName() << ").\n");
4145 return false;
4146 }
4147
4148 if (VPH.canCombine(ToBePromoted)) {
4149 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4150 << "will be combined with: " << *ToBePromoted << '\n');
4151 VPH.recordCombineInstruction(ToBePromoted);
4152 bool Changed = VPH.promote();
4153 NumStoreExtractExposed += Changed;
4154 return Changed;
4155 }
4156
4157 DEBUG(dbgs() << "Try promoting.\n");
4158 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4159 return false;
4160
4161 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4162
4163 VPH.enqueueForPromotion(ToBePromoted);
4164 Inst = ToBePromoted;
4165 }
4166 return false;
4167 }
4168
OptimizeInst(Instruction * I,bool & ModifiedDT)4169 bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
4170 if (PHINode *P = dyn_cast<PHINode>(I)) {
4171 // It is possible for very late stage optimizations (such as SimplifyCFG)
4172 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4173 // trivial PHI, go ahead and zap it here.
4174 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
4175 TLInfo, DT)) {
4176 P->replaceAllUsesWith(V);
4177 P->eraseFromParent();
4178 ++NumPHIsElim;
4179 return true;
4180 }
4181 return false;
4182 }
4183
4184 if (CastInst *CI = dyn_cast<CastInst>(I)) {
4185 // If the source of the cast is a constant, then this should have
4186 // already been constant folded. The only reason NOT to constant fold
4187 // it is if something (e.g. LSR) was careful to place the constant
4188 // evaluation in a block other than then one that uses it (e.g. to hoist
4189 // the address of globals out of a loop). If this is the case, we don't
4190 // want to forward-subst the cast.
4191 if (isa<Constant>(CI->getOperand(0)))
4192 return false;
4193
4194 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
4195 return true;
4196
4197 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
4198 /// Sink a zext or sext into its user blocks if the target type doesn't
4199 /// fit in one register
4200 if (TLI && TLI->getTypeAction(CI->getContext(),
4201 TLI->getValueType(CI->getType())) ==
4202 TargetLowering::TypeExpandInteger) {
4203 return SinkCast(CI);
4204 } else {
4205 bool MadeChange = MoveExtToFormExtLoad(I);
4206 return MadeChange | OptimizeExtUses(I);
4207 }
4208 }
4209 return false;
4210 }
4211
4212 if (CmpInst *CI = dyn_cast<CmpInst>(I))
4213 if (!TLI || !TLI->hasMultipleConditionRegisters())
4214 return OptimizeCmpExpression(CI);
4215
4216 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4217 if (TLI)
4218 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
4219 return false;
4220 }
4221
4222 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4223 if (TLI)
4224 return OptimizeMemoryInst(I, SI->getOperand(1),
4225 SI->getOperand(0)->getType());
4226 return false;
4227 }
4228
4229 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4230
4231 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4232 BinOp->getOpcode() == Instruction::LShr)) {
4233 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4234 if (TLI && CI && TLI->hasExtractBitsInsn())
4235 return OptimizeExtractBits(BinOp, CI, *TLI);
4236
4237 return false;
4238 }
4239
4240 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
4241 if (GEPI->hasAllZeroIndices()) {
4242 /// The GEP operand must be a pointer, so must its result -> BitCast
4243 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4244 GEPI->getName(), GEPI);
4245 GEPI->replaceAllUsesWith(NC);
4246 GEPI->eraseFromParent();
4247 ++NumGEPsElim;
4248 OptimizeInst(NC, ModifiedDT);
4249 return true;
4250 }
4251 return false;
4252 }
4253
4254 if (CallInst *CI = dyn_cast<CallInst>(I))
4255 return OptimizeCallInst(CI, ModifiedDT);
4256
4257 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4258 return OptimizeSelectInst(SI);
4259
4260 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4261 return OptimizeShuffleVectorInst(SVI);
4262
4263 if (isa<ExtractElementInst>(I))
4264 return OptimizeExtractElementInst(I);
4265
4266 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
4267 if (TLI && BI->isConditional() && BI->getCondition()->hasOneUse()) {
4268 // Check if the branch condition compares a value agaist zero.
4269 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
4270 if (ICI->getPredicate() == ICmpInst::ICMP_EQ &&
4271 match(ICI->getOperand(1), m_Zero())) {
4272 BasicBlock *ThenBB = BI->getSuccessor(1);
4273 BasicBlock *EndBB = BI->getSuccessor(0);
4274
4275 // Check if ThenBB is only reachable from this basic block; also,
4276 // check if EndBB has more than one predecessor.
4277 if (ThenBB->getSinglePredecessor() &&
4278 !EndBB->getSinglePredecessor()) {
4279 TerminatorInst *TI = ThenBB->getTerminator();
4280
4281 if (TI->getNumSuccessors() == 1 && TI->getSuccessor(0) == EndBB &&
4282 // Try to speculate calls to intrinsic cttz/ctlz from 'ThenBB'.
4283 OptimizeBranchInst(BI, *TLI)) {
4284 ModifiedDT = true;
4285 return true;
4286 }
4287 }
4288 }
4289 }
4290 }
4291 return false;
4292 }
4293
4294 return false;
4295 }
4296
4297 // In this pass we look for GEP and cast instructions that are used
4298 // across basic blocks and rewrite them to improve basic-block-at-a-time
4299 // selection.
OptimizeBlock(BasicBlock & BB,bool & ModifiedDT)4300 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
4301 SunkAddrs.clear();
4302 bool MadeChange = false;
4303
4304 CurInstIterator = BB.begin();
4305 while (CurInstIterator != BB.end()) {
4306 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4307 if (ModifiedDT)
4308 return true;
4309 }
4310 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4311
4312 return MadeChange;
4313 }
4314
4315 // llvm.dbg.value is far away from the value then iSel may not be able
4316 // handle it properly. iSel will drop llvm.dbg.value if it can not
4317 // find a node corresponding to the value.
PlaceDbgValues(Function & F)4318 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4319 bool MadeChange = false;
4320 for (BasicBlock &BB : F) {
4321 Instruction *PrevNonDbgInst = nullptr;
4322 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
4323 Instruction *Insn = BI++;
4324 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
4325 // Leave dbg.values that refer to an alloca alone. These
4326 // instrinsics describe the address of a variable (= the alloca)
4327 // being taken. They should not be moved next to the alloca
4328 // (and to the beginning of the scope), but rather stay close to
4329 // where said address is used.
4330 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
4331 PrevNonDbgInst = Insn;
4332 continue;
4333 }
4334
4335 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4336 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4337 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4338 DVI->removeFromParent();
4339 if (isa<PHINode>(VI))
4340 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4341 else
4342 DVI->insertAfter(VI);
4343 MadeChange = true;
4344 ++NumDbgValueMoved;
4345 }
4346 }
4347 }
4348 return MadeChange;
4349 }
4350
4351 // If there is a sequence that branches based on comparing a single bit
4352 // against zero that can be combined into a single instruction, and the
4353 // target supports folding these into a single instruction, sink the
4354 // mask and compare into the branch uses. Do this before OptimizeBlock ->
4355 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4356 // searched for.
sinkAndCmp(Function & F)4357 bool CodeGenPrepare::sinkAndCmp(Function &F) {
4358 if (!EnableAndCmpSinking)
4359 return false;
4360 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4361 return false;
4362 bool MadeChange = false;
4363 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4364 BasicBlock *BB = I++;
4365
4366 // Does this BB end with the following?
4367 // %andVal = and %val, #single-bit-set
4368 // %icmpVal = icmp %andResult, 0
4369 // br i1 %cmpVal label %dest1, label %dest2"
4370 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4371 if (!Brcc || !Brcc->isConditional())
4372 continue;
4373 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4374 if (!Cmp || Cmp->getParent() != BB)
4375 continue;
4376 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4377 if (!Zero || !Zero->isZero())
4378 continue;
4379 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4380 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4381 continue;
4382 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4383 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4384 continue;
4385 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4386
4387 // Push the "and; icmp" for any users that are conditional branches.
4388 // Since there can only be one branch use per BB, we don't need to keep
4389 // track of which BBs we insert into.
4390 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4391 UI != E; ) {
4392 Use &TheUse = *UI;
4393 // Find brcc use.
4394 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4395 ++UI;
4396 if (!BrccUser || !BrccUser->isConditional())
4397 continue;
4398 BasicBlock *UserBB = BrccUser->getParent();
4399 if (UserBB == BB) continue;
4400 DEBUG(dbgs() << "found Brcc use\n");
4401
4402 // Sink the "and; icmp" to use.
4403 MadeChange = true;
4404 BinaryOperator *NewAnd =
4405 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4406 BrccUser);
4407 CmpInst *NewCmp =
4408 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4409 "", BrccUser);
4410 TheUse = NewCmp;
4411 ++NumAndCmpsMoved;
4412 DEBUG(BrccUser->getParent()->dump());
4413 }
4414 }
4415 return MadeChange;
4416 }
4417
4418 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
4419 /// success, or returns false if no or invalid metadata was found.
extractBranchMetadata(BranchInst * BI,uint64_t & ProbTrue,uint64_t & ProbFalse)4420 static bool extractBranchMetadata(BranchInst *BI,
4421 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4422 assert(BI->isConditional() &&
4423 "Looking for probabilities on unconditional branch?");
4424 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4425 if (!ProfileData || ProfileData->getNumOperands() != 3)
4426 return false;
4427
4428 const auto *CITrue =
4429 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4430 const auto *CIFalse =
4431 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
4432 if (!CITrue || !CIFalse)
4433 return false;
4434
4435 ProbTrue = CITrue->getValue().getZExtValue();
4436 ProbFalse = CIFalse->getValue().getZExtValue();
4437
4438 return true;
4439 }
4440
4441 /// \brief Scale down both weights to fit into uint32_t.
scaleWeights(uint64_t & NewTrue,uint64_t & NewFalse)4442 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4443 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4444 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4445 NewTrue = NewTrue / Scale;
4446 NewFalse = NewFalse / Scale;
4447 }
4448
4449 /// \brief Some targets prefer to split a conditional branch like:
4450 /// \code
4451 /// %0 = icmp ne i32 %a, 0
4452 /// %1 = icmp ne i32 %b, 0
4453 /// %or.cond = or i1 %0, %1
4454 /// br i1 %or.cond, label %TrueBB, label %FalseBB
4455 /// \endcode
4456 /// into multiple branch instructions like:
4457 /// \code
4458 /// bb1:
4459 /// %0 = icmp ne i32 %a, 0
4460 /// br i1 %0, label %TrueBB, label %bb2
4461 /// bb2:
4462 /// %1 = icmp ne i32 %b, 0
4463 /// br i1 %1, label %TrueBB, label %FalseBB
4464 /// \endcode
4465 /// This usually allows instruction selection to do even further optimizations
4466 /// and combine the compare with the branch instruction. Currently this is
4467 /// applied for targets which have "cheap" jump instructions.
4468 ///
4469 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4470 ///
splitBranchCondition(Function & F)4471 bool CodeGenPrepare::splitBranchCondition(Function &F) {
4472 if (!TM || TM->Options.EnableFastISel != true ||
4473 !TLI || TLI->isJumpExpensive())
4474 return false;
4475
4476 bool MadeChange = false;
4477 for (auto &BB : F) {
4478 // Does this BB end with the following?
4479 // %cond1 = icmp|fcmp|binary instruction ...
4480 // %cond2 = icmp|fcmp|binary instruction ...
4481 // %cond.or = or|and i1 %cond1, cond2
4482 // br i1 %cond.or label %dest1, label %dest2"
4483 BinaryOperator *LogicOp;
4484 BasicBlock *TBB, *FBB;
4485 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4486 continue;
4487
4488 unsigned Opc;
4489 Value *Cond1, *Cond2;
4490 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4491 m_OneUse(m_Value(Cond2)))))
4492 Opc = Instruction::And;
4493 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4494 m_OneUse(m_Value(Cond2)))))
4495 Opc = Instruction::Or;
4496 else
4497 continue;
4498
4499 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4500 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4501 continue;
4502
4503 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4504
4505 // Create a new BB.
4506 auto *InsertBefore = std::next(Function::iterator(BB))
4507 .getNodePtrUnchecked();
4508 auto TmpBB = BasicBlock::Create(BB.getContext(),
4509 BB.getName() + ".cond.split",
4510 BB.getParent(), InsertBefore);
4511
4512 // Update original basic block by using the first condition directly by the
4513 // branch instruction and removing the no longer needed and/or instruction.
4514 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4515 Br1->setCondition(Cond1);
4516 LogicOp->eraseFromParent();
4517
4518 // Depending on the conditon we have to either replace the true or the false
4519 // successor of the original branch instruction.
4520 if (Opc == Instruction::And)
4521 Br1->setSuccessor(0, TmpBB);
4522 else
4523 Br1->setSuccessor(1, TmpBB);
4524
4525 // Fill in the new basic block.
4526 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
4527 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4528 I->removeFromParent();
4529 I->insertBefore(Br2);
4530 }
4531
4532 // Update PHI nodes in both successors. The original BB needs to be
4533 // replaced in one succesor's PHI nodes, because the branch comes now from
4534 // the newly generated BB (NewBB). In the other successor we need to add one
4535 // incoming edge to the PHI nodes, because both branch instructions target
4536 // now the same successor. Depending on the original branch condition
4537 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4538 // we perfrom the correct update for the PHI nodes.
4539 // This doesn't change the successor order of the just created branch
4540 // instruction (or any other instruction).
4541 if (Opc == Instruction::Or)
4542 std::swap(TBB, FBB);
4543
4544 // Replace the old BB with the new BB.
4545 for (auto &I : *TBB) {
4546 PHINode *PN = dyn_cast<PHINode>(&I);
4547 if (!PN)
4548 break;
4549 int i;
4550 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4551 PN->setIncomingBlock(i, TmpBB);
4552 }
4553
4554 // Add another incoming edge form the new BB.
4555 for (auto &I : *FBB) {
4556 PHINode *PN = dyn_cast<PHINode>(&I);
4557 if (!PN)
4558 break;
4559 auto *Val = PN->getIncomingValueForBlock(&BB);
4560 PN->addIncoming(Val, TmpBB);
4561 }
4562
4563 // Update the branch weights (from SelectionDAGBuilder::
4564 // FindMergedConditions).
4565 if (Opc == Instruction::Or) {
4566 // Codegen X | Y as:
4567 // BB1:
4568 // jmp_if_X TBB
4569 // jmp TmpBB
4570 // TmpBB:
4571 // jmp_if_Y TBB
4572 // jmp FBB
4573 //
4574
4575 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4576 // The requirement is that
4577 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4578 // = TrueProb for orignal BB.
4579 // Assuming the orignal weights are A and B, one choice is to set BB1's
4580 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4581 // assumes that
4582 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4583 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4584 // TmpBB, but the math is more complicated.
4585 uint64_t TrueWeight, FalseWeight;
4586 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4587 uint64_t NewTrueWeight = TrueWeight;
4588 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4589 scaleWeights(NewTrueWeight, NewFalseWeight);
4590 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4591 .createBranchWeights(TrueWeight, FalseWeight));
4592
4593 NewTrueWeight = TrueWeight;
4594 NewFalseWeight = 2 * FalseWeight;
4595 scaleWeights(NewTrueWeight, NewFalseWeight);
4596 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4597 .createBranchWeights(TrueWeight, FalseWeight));
4598 }
4599 } else {
4600 // Codegen X & Y as:
4601 // BB1:
4602 // jmp_if_X TmpBB
4603 // jmp FBB
4604 // TmpBB:
4605 // jmp_if_Y TBB
4606 // jmp FBB
4607 //
4608 // This requires creation of TmpBB after CurBB.
4609
4610 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4611 // The requirement is that
4612 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4613 // = FalseProb for orignal BB.
4614 // Assuming the orignal weights are A and B, one choice is to set BB1's
4615 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4616 // assumes that
4617 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4618 uint64_t TrueWeight, FalseWeight;
4619 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4620 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4621 uint64_t NewFalseWeight = FalseWeight;
4622 scaleWeights(NewTrueWeight, NewFalseWeight);
4623 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4624 .createBranchWeights(TrueWeight, FalseWeight));
4625
4626 NewTrueWeight = 2 * TrueWeight;
4627 NewFalseWeight = FalseWeight;
4628 scaleWeights(NewTrueWeight, NewFalseWeight);
4629 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4630 .createBranchWeights(TrueWeight, FalseWeight));
4631 }
4632 }
4633
4634 // Request DOM Tree update.
4635 // Note: No point in getting fancy here, since the DT info is never
4636 // available to CodeGenPrepare and the existing update code is broken
4637 // anyways.
4638 ModifiedDT = true;
4639
4640 MadeChange = true;
4641
4642 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4643 TmpBB->dump());
4644 }
4645 return MadeChange;
4646 }
4647