LLVM 17.0.0git
CodeGenPrepare.cpp
Go to the documentation of this file.
1//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
10// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/Statistic.h"
41#include "llvm/Config/llvm-config.h"
42#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/Constant.h"
46#include "llvm/IR/Constants.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DebugInfo.h"
50#include "llvm/IR/Dominators.h"
51#include "llvm/IR/Function.h"
53#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
57#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
61#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/IntrinsicsAArch64.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/MDBuilder.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
69#include "llvm/IR/Statepoint.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
74#include "llvm/IR/ValueHandle.h"
75#include "llvm/IR/ValueMap.h"
77#include "llvm/Pass.h"
83#include "llvm/Support/Debug.h"
95#include <algorithm>
96#include <cassert>
97#include <cstdint>
98#include <iterator>
99#include <limits>
100#include <memory>
101#include <optional>
102#include <utility>
103#include <vector>
104
105using namespace llvm;
106using namespace llvm::PatternMatch;
107
108#define DEBUG_TYPE "codegenprepare"
109
110STATISTIC(NumBlocksElim, "Number of blocks eliminated");
111STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
112STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
113STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
114 "sunken Cmps");
115STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
116 "of sunken Casts");
117STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
118 "computations were sunk");
119STATISTIC(NumMemoryInstsPhiCreated,
120 "Number of phis created when address "
121 "computations were sunk to memory instructions");
122STATISTIC(NumMemoryInstsSelectCreated,
123 "Number of select created when address "
124 "computations were sunk to memory instructions");
125STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
126STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
127STATISTIC(NumAndsAdded,
128 "Number of and mask instructions added to form ext loads");
129STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
130STATISTIC(NumRetsDup, "Number of return instructions duplicated");
131STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
132STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
133STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
134
136 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
137 cl::desc("Disable branch optimizations in CodeGenPrepare"));
138
139static cl::opt<bool>
140 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
141 cl::desc("Disable GC optimizations in CodeGenPrepare"));
142
143static cl::opt<bool>
144 DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden,
145 cl::init(false),
146 cl::desc("Disable select to branch conversion."));
147
148static cl::opt<bool>
149 AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true),
150 cl::desc("Address sinking in CGP using GEPs."));
151
152static cl::opt<bool>
153 EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true),
154 cl::desc("Enable sinkinig and/cmp into branches."));
155
157 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
158 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
159
161 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
162 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
163
165 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
166 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
167 "CodeGenPrepare"));
168
170 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
171 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
172 "optimization in CodeGenPrepare"));
173
175 "disable-preheader-prot", cl::Hidden, cl::init(false),
176 cl::desc("Disable protection against removing loop preheaders"));
177
179 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
180 cl::desc("Use profile info to add section prefix for hot/cold functions"));
181
183 "profile-unknown-in-special-section", cl::Hidden,
184 cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
185 "profile, we cannot tell the function is cold for sure because "
186 "it may be a function newly added without ever being sampled. "
187 "With the flag enabled, compiler can put such profile unknown "
188 "functions into a special section, so runtime system can choose "
189 "to handle it in a different way than .text section, to save "
190 "RAM for example. "));
191
193 "bbsections-guided-section-prefix", cl::Hidden, cl::init(true),
194 cl::desc("Use the basic-block-sections profile to determine the text "
195 "section prefix for hot functions. Functions with "
196 "basic-block-sections profile will be placed in `.text.hot` "
197 "regardless of their FDO profile info. Other functions won't be "
198 "impacted, i.e., their prefixes will be decided by FDO/sampleFDO "
199 "profiles."));
200
202 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
203 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
204 "(frequency of destination block) is greater than this ratio"));
205
207 "force-split-store", cl::Hidden, cl::init(false),
208 cl::desc("Force store splitting no matter what the target query says."));
209
211 "cgp-type-promotion-merge", cl::Hidden,
212 cl::desc("Enable merging of redundant sexts when one is dominating"
213 " the other."),
214 cl::init(true));
215
217 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
218 cl::desc("Disables combining addressing modes with different parts "
219 "in optimizeMemoryInst."));
220
221static cl::opt<bool>
222 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
223 cl::desc("Allow creation of Phis in Address sinking."));
224
226 "addr-sink-new-select", cl::Hidden, cl::init(true),
227 cl::desc("Allow creation of selects in Address sinking."));
228
230 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
231 cl::desc("Allow combining of BaseReg field in Address sinking."));
232
234 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
235 cl::desc("Allow combining of BaseGV field in Address sinking."));
236
238 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
239 cl::desc("Allow combining of BaseOffs field in Address sinking."));
240
242 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
243 cl::desc("Allow combining of ScaledReg field in Address sinking."));
244
245static cl::opt<bool>
246 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
247 cl::init(true),
248 cl::desc("Enable splitting large offset of GEP."));
249
251 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
252 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
253
254static cl::opt<bool>
255 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
256 cl::desc("Enable BFI update verification for "
257 "CodeGenPrepare."));
258
259static cl::opt<bool>
260 OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(false),
261 cl::desc("Enable converting phi types in CodeGenPrepare"));
262
264 HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden,
265 cl::desc("Least BB number of huge function."));
266
267namespace {
268
269enum ExtType {
270 ZeroExtension, // Zero extension has been seen.
271 SignExtension, // Sign extension has been seen.
272 BothExtension // This extension type is used if we saw sext after
273 // ZeroExtension had been set, or if we saw zext after
274 // SignExtension had been set. It makes the type
275 // information of a promoted instruction invalid.
276};
277
278enum ModifyDT {
279 NotModifyDT, // Not Modify any DT.
280 ModifyBBDT, // Modify the Basic Block Dominator Tree.
281 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
282 // This usually means we move/delete/insert instruction
283 // in a Basic Block. So we should re-iterate instructions
284 // in such Basic Block.
285};
286
287using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
288using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
289using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
291using ValueToSExts = MapVector<Value *, SExts>;
292
293class TypePromotionTransaction;
294
295class CodeGenPrepare : public FunctionPass {
296 const TargetMachine *TM = nullptr;
297 const TargetSubtargetInfo *SubtargetInfo;
298 const TargetLowering *TLI = nullptr;
299 const TargetRegisterInfo *TRI;
300 const TargetTransformInfo *TTI = nullptr;
301 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
302 const TargetLibraryInfo *TLInfo;
303 const LoopInfo *LI;
304 std::unique_ptr<BlockFrequencyInfo> BFI;
305 std::unique_ptr<BranchProbabilityInfo> BPI;
307
308 /// As we scan instructions optimizing them, this is the next instruction
309 /// to optimize. Transforms that can invalidate this should update it.
310 BasicBlock::iterator CurInstIterator;
311
312 /// Keeps track of non-local addresses that have been sunk into a block.
313 /// This allows us to avoid inserting duplicate code for blocks with
314 /// multiple load/stores of the same address. The usage of WeakTrackingVH
315 /// enables SunkAddrs to be treated as a cache whose entries can be
316 /// invalidated if a sunken address computation has been erased.
318
319 /// Keeps track of all instructions inserted for the current function.
320 SetOfInstrs InsertedInsts;
321
322 /// Keeps track of the type of the related instruction before their
323 /// promotion for the current function.
324 InstrToOrigTy PromotedInsts;
325
326 /// Keep track of instructions removed during promotion.
327 SetOfInstrs RemovedInsts;
328
329 /// Keep track of sext chains based on their initial value.
330 DenseMap<Value *, Instruction *> SeenChainsForSExt;
331
332 /// Keep track of GEPs accessing the same data structures such as structs or
333 /// arrays that are candidates to be split later because of their large
334 /// size.
337 LargeOffsetGEPMap;
338
339 /// Keep track of new GEP base after splitting the GEPs having large offset.
340 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
341
342 /// Map serial numbers to Large offset GEPs.
343 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
344
345 /// Keep track of SExt promoted.
346 ValueToSExts ValToSExtendedUses;
347
348 /// True if the function has the OptSize attribute.
349 bool OptSize;
350
351 /// DataLayout for the Function being processed.
352 const DataLayout *DL = nullptr;
353
354 /// Building the dominator tree can be expensive, so we only build it
355 /// lazily and update it when required.
356 std::unique_ptr<DominatorTree> DT;
357
358public:
359 /// If encounter huge function, we need to limit the build time.
360 bool IsHugeFunc = false;
361
362 /// FreshBBs is like worklist, it collected the updated BBs which need
363 /// to be optimized again.
364 /// Note: Consider building time in this pass, when a BB updated, we need
365 /// to insert such BB into FreshBBs for huge function.
367
368 static char ID; // Pass identification, replacement for typeid
369
370 CodeGenPrepare() : FunctionPass(ID) {
372 }
373
374 bool runOnFunction(Function &F) override;
375
376 StringRef getPassName() const override { return "CodeGen Prepare"; }
377
378 void getAnalysisUsage(AnalysisUsage &AU) const override {
379 // FIXME: When we can selectively preserve passes, preserve the domtree.
386 }
387
388private:
389 template <typename F>
390 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
391 // Substituting can cause recursive simplifications, which can invalidate
392 // our iterator. Use a WeakTrackingVH to hold onto it in case this
393 // happens.
394 Value *CurValue = &*CurInstIterator;
395 WeakTrackingVH IterHandle(CurValue);
396
397 f();
398
399 // If the iterator instruction was recursively deleted, start over at the
400 // start of the block.
401 if (IterHandle != CurValue) {
402 CurInstIterator = BB->begin();
403 SunkAddrs.clear();
404 }
405 }
406
407 // Get the DominatorTree, building if necessary.
408 DominatorTree &getDT(Function &F) {
409 if (!DT)
410 DT = std::make_unique<DominatorTree>(F);
411 return *DT;
412 }
413
414 void removeAllAssertingVHReferences(Value *V);
415 bool eliminateAssumptions(Function &F);
416 bool eliminateFallThrough(Function &F);
417 bool eliminateMostlyEmptyBlocks(Function &F);
418 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
419 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
420 void eliminateMostlyEmptyBlock(BasicBlock *BB);
421 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
422 bool isPreheader);
423 bool makeBitReverse(Instruction &I);
424 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
425 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
426 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
427 unsigned AddrSpace);
428 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
429 bool optimizeInlineAsmInst(CallInst *CS);
430 bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
431 bool optimizeExt(Instruction *&I);
432 bool optimizeExtUses(Instruction *I);
433 bool optimizeLoadExt(LoadInst *Load);
434 bool optimizeShiftInst(BinaryOperator *BO);
435 bool optimizeFunnelShift(IntrinsicInst *Fsh);
436 bool optimizeSelectInst(SelectInst *SI);
437 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
438 bool optimizeSwitchType(SwitchInst *SI);
439 bool optimizeSwitchPhiConstants(SwitchInst *SI);
440 bool optimizeSwitchInst(SwitchInst *SI);
441 bool optimizeExtractElementInst(Instruction *Inst);
442 bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
443 bool fixupDbgValue(Instruction *I);
444 bool placeDbgValues(Function &F);
445 bool placePseudoProbes(Function &F);
446 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
447 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
448 bool tryToPromoteExts(TypePromotionTransaction &TPT,
450 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
451 unsigned CreatedInstsCost = 0);
452 bool mergeSExts(Function &F);
453 bool splitLargeGEPOffsets();
454 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
455 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
456 bool optimizePhiTypes(Function &F);
457 bool performAddressTypePromotion(
458 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
459 bool HasPromoted, TypePromotionTransaction &TPT,
460 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
461 bool splitBranchCondition(Function &F, ModifyDT &ModifiedDT);
462 bool simplifyOffsetableRelocate(GCStatepointInst &I);
463
464 bool tryToSinkFreeOperands(Instruction *I);
465 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
466 CmpInst *Cmp, Intrinsic::ID IID);
467 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
468 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
469 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
470 void verifyBFIUpdates(Function &F);
471};
472
473} // end anonymous namespace
474
475char CodeGenPrepare::ID = 0;
476
478 "Optimize for code generation", false, false)
485INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, "Optimize for code generation",
487
488FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
489
490bool CodeGenPrepare::runOnFunction(Function &F) {
491 if (skipFunction(F))
492 return false;
493
494 DL = &F.getParent()->getDataLayout();
495
496 bool EverMadeChange = false;
497 // Clear per function information.
498 InsertedInsts.clear();
499 PromotedInsts.clear();
500 FreshBBs.clear();
501
502 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
503 SubtargetInfo = TM->getSubtargetImpl(F);
504 TLI = SubtargetInfo->getTargetLowering();
505 TRI = SubtargetInfo->getRegisterInfo();
506 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
507 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
508 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
509 BPI.reset(new BranchProbabilityInfo(F, *LI));
510 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
511 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
512 BBSectionsProfileReader =
513 getAnalysisIfAvailable<BasicBlockSectionsProfileReader>();
514 OptSize = F.hasOptSize();
515 // Use the basic-block-sections profile to promote hot functions to .text.hot
516 // if requested.
517 if (BBSectionsGuidedSectionPrefix && BBSectionsProfileReader &&
518 BBSectionsProfileReader->isFunctionHot(F.getName())) {
519 F.setSectionPrefix("hot");
520 } else if (ProfileGuidedSectionPrefix) {
521 // The hot attribute overwrites profile count based hotness while profile
522 // counts based hotness overwrite the cold attribute.
523 // This is a conservative behabvior.
524 if (F.hasFnAttribute(Attribute::Hot) ||
525 PSI->isFunctionHotInCallGraph(&F, *BFI))
526 F.setSectionPrefix("hot");
527 // If PSI shows this function is not hot, we will placed the function
528 // into unlikely section if (1) PSI shows this is a cold function, or
529 // (2) the function has a attribute of cold.
530 else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
531 F.hasFnAttribute(Attribute::Cold))
532 F.setSectionPrefix("unlikely");
535 F.setSectionPrefix("unknown");
536 }
537
538 /// This optimization identifies DIV instructions that can be
539 /// profitably bypassed and carried out with a shorter, faster divide.
540 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
541 const DenseMap<unsigned int, unsigned int> &BypassWidths =
543 BasicBlock *BB = &*F.begin();
544 while (BB != nullptr) {
545 // bypassSlowDivision may create new BBs, but we don't want to reapply the
546 // optimization to those blocks.
547 BasicBlock *Next = BB->getNextNode();
548 // F.hasOptSize is already checked in the outer if statement.
549 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
550 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
551 BB = Next;
552 }
553 }
554
555 // Get rid of @llvm.assume builtins before attempting to eliminate empty
556 // blocks, since there might be blocks that only contain @llvm.assume calls
557 // (plus arguments that we can get rid of).
558 EverMadeChange |= eliminateAssumptions(F);
559
560 // Eliminate blocks that contain only PHI nodes and an
561 // unconditional branch.
562 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
563
564 ModifyDT ModifiedDT = ModifyDT::NotModifyDT;
566 EverMadeChange |= splitBranchCondition(F, ModifiedDT);
567
568 // Split some critical edges where one of the sources is an indirect branch,
569 // to help generate sane code for PHIs involving such edges.
570 EverMadeChange |=
571 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
572
573 // If we are optimzing huge function, we need to consider the build time.
574 // Because the basic algorithm's complex is near O(N!).
575 IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;
576
577 bool MadeChange = true;
578 bool FuncIterated = false;
579 while (MadeChange) {
580 MadeChange = false;
581 DT.reset();
582
584 if (FuncIterated && !FreshBBs.contains(&BB))
585 continue;
586
587 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
588 bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
589
590 MadeChange |= Changed;
591 if (IsHugeFunc) {
592 // If the BB is updated, it may still has chance to be optimized.
593 // This usually happen at sink optimization.
594 // For example:
595 //
596 // bb0:
597 // %and = and i32 %a, 4
598 // %cmp = icmp eq i32 %and, 0
599 //
600 // If the %cmp sink to other BB, the %and will has chance to sink.
601 if (Changed)
602 FreshBBs.insert(&BB);
603 else if (FuncIterated)
604 FreshBBs.erase(&BB);
605
606 if (ModifiedDTOnIteration == ModifyDT::ModifyBBDT)
607 DT.reset();
608 } else {
609 // For small/normal functions, we restart BB iteration if the dominator
610 // tree of the Function was changed.
611 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
612 break;
613 }
614 }
615 // We have iterated all the BB in the (only work for huge) function.
616 FuncIterated = IsHugeFunc;
617
618 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
619 MadeChange |= mergeSExts(F);
620 if (!LargeOffsetGEPMap.empty())
621 MadeChange |= splitLargeGEPOffsets();
622 MadeChange |= optimizePhiTypes(F);
623
624 if (MadeChange)
625 eliminateFallThrough(F);
626
627 // Really free removed instructions during promotion.
628 for (Instruction *I : RemovedInsts)
629 I->deleteValue();
630
631 EverMadeChange |= MadeChange;
632 SeenChainsForSExt.clear();
633 ValToSExtendedUses.clear();
634 RemovedInsts.clear();
635 LargeOffsetGEPMap.clear();
636 LargeOffsetGEPID.clear();
637 }
638
639 NewGEPBases.clear();
640 SunkAddrs.clear();
641
642 if (!DisableBranchOpts) {
643 MadeChange = false;
644 // Use a set vector to get deterministic iteration order. The order the
645 // blocks are removed may affect whether or not PHI nodes in successors
646 // are removed.
648 for (BasicBlock &BB : F) {
650 MadeChange |= ConstantFoldTerminator(&BB, true);
651 if (!MadeChange)
652 continue;
653
654 for (BasicBlock *Succ : Successors)
655 if (pred_empty(Succ))
656 WorkList.insert(Succ);
657 }
658
659 // Delete the dead blocks and any of their dead successors.
660 MadeChange |= !WorkList.empty();
661 while (!WorkList.empty()) {
662 BasicBlock *BB = WorkList.pop_back_val();
664
665 DeleteDeadBlock(BB);
666
667 for (BasicBlock *Succ : Successors)
668 if (pred_empty(Succ))
669 WorkList.insert(Succ);
670 }
671
672 // Merge pairs of basic blocks with unconditional branches, connected by
673 // a single edge.
674 if (EverMadeChange || MadeChange)
675 MadeChange |= eliminateFallThrough(F);
676
677 EverMadeChange |= MadeChange;
678 }
679
680 if (!DisableGCOpts) {
682 for (BasicBlock &BB : F)
683 for (Instruction &I : BB)
684 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
685 Statepoints.push_back(SP);
686 for (auto &I : Statepoints)
687 EverMadeChange |= simplifyOffsetableRelocate(*I);
688 }
689
690 // Do this last to clean up use-before-def scenarios introduced by other
691 // preparatory transforms.
692 EverMadeChange |= placeDbgValues(F);
693 EverMadeChange |= placePseudoProbes(F);
694
695#ifndef NDEBUG
697 verifyBFIUpdates(F);
698#endif
699
700 return EverMadeChange;
701}
702
703bool CodeGenPrepare::eliminateAssumptions(Function &F) {
704 bool MadeChange = false;
705 for (BasicBlock &BB : F) {
706 CurInstIterator = BB.begin();
707 while (CurInstIterator != BB.end()) {
708 Instruction *I = &*(CurInstIterator++);
709 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
710 MadeChange = true;
711 Value *Operand = Assume->getOperand(0);
712 Assume->eraseFromParent();
713
714 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
715 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
716 });
717 }
718 }
719 }
720 return MadeChange;
721}
722
723/// An instruction is about to be deleted, so remove all references to it in our
724/// GEP-tracking data strcutures.
725void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
726 LargeOffsetGEPMap.erase(V);
727 NewGEPBases.erase(V);
728
729 auto GEP = dyn_cast<GetElementPtrInst>(V);
730 if (!GEP)
731 return;
732
733 LargeOffsetGEPID.erase(GEP);
734
735 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
736 if (VecI == LargeOffsetGEPMap.end())
737 return;
738
739 auto &GEPVector = VecI->second;
740 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
741
742 if (GEPVector.empty())
743 LargeOffsetGEPMap.erase(VecI);
744}
745
746// Verify BFI has been updated correctly by recomputing BFI and comparing them.
747void LLVM_ATTRIBUTE_UNUSED CodeGenPrepare::verifyBFIUpdates(Function &F) {
748 DominatorTree NewDT(F);
749 LoopInfo NewLI(NewDT);
750 BranchProbabilityInfo NewBPI(F, NewLI, TLInfo);
751 BlockFrequencyInfo NewBFI(F, NewBPI, NewLI);
752 NewBFI.verifyMatch(*BFI);
753}
754
755/// Merge basic blocks which are connected by a single edge, where one of the
756/// basic blocks has a single successor pointing to the other basic block,
757/// which has a single predecessor.
758bool CodeGenPrepare::eliminateFallThrough(Function &F) {
759 bool Changed = false;
760 // Scan all of the blocks in the function, except for the entry block.
761 // Use a temporary array to avoid iterator being invalidated when
762 // deleting blocks.
764 for (auto &Block : llvm::drop_begin(F))
765 Blocks.push_back(&Block);
766
768 for (auto &Block : Blocks) {
769 auto *BB = cast_or_null<BasicBlock>(Block);
770 if (!BB)
771 continue;
772 // If the destination block has a single pred, then this is a trivial
773 // edge, just collapse it.
774 BasicBlock *SinglePred = BB->getSinglePredecessor();
775
776 // Don't merge if BB's address is taken.
777 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
778 continue;
779
780 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
781 if (Term && !Term->isConditional()) {
782 Changed = true;
783 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
784
785 // Merge BB into SinglePred and delete it.
787 Preds.insert(SinglePred);
788
789 if (IsHugeFunc) {
790 // Update FreshBBs to optimize the merged BB.
791 FreshBBs.insert(SinglePred);
792 FreshBBs.erase(BB);
793 }
794 }
795 }
796
797 // (Repeatedly) merging blocks into their predecessors can create redundant
798 // debug intrinsics.
799 for (const auto &Pred : Preds)
800 if (auto *BB = cast_or_null<BasicBlock>(Pred))
802
803 return Changed;
804}
805
806/// Find a destination block from BB if BB is mergeable empty block.
807BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
808 // If this block doesn't end with an uncond branch, ignore it.
809 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
810 if (!BI || !BI->isUnconditional())
811 return nullptr;
812
813 // If the instruction before the branch (skipping debug info) isn't a phi
814 // node, then other stuff is happening here.
816 if (BBI != BB->begin()) {
817 --BBI;
818 while (isa<DbgInfoIntrinsic>(BBI)) {
819 if (BBI == BB->begin())
820 break;
821 --BBI;
822 }
823 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
824 return nullptr;
825 }
826
827 // Do not break infinite loops.
828 BasicBlock *DestBB = BI->getSuccessor(0);
829 if (DestBB == BB)
830 return nullptr;
831
832 if (!canMergeBlocks(BB, DestBB))
833 DestBB = nullptr;
834
835 return DestBB;
836}
837
838/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
839/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
840/// edges in ways that are non-optimal for isel. Start by eliminating these
841/// blocks so we can split them the way we want them.
842bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
844 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
845 while (!LoopList.empty()) {
846 Loop *L = LoopList.pop_back_val();
847 llvm::append_range(LoopList, *L);
848 if (BasicBlock *Preheader = L->getLoopPreheader())
849 Preheaders.insert(Preheader);
850 }
851
852 bool MadeChange = false;
853 // Copy blocks into a temporary array to avoid iterator invalidation issues
854 // as we remove them.
855 // Note that this intentionally skips the entry block.
857 for (auto &Block : llvm::drop_begin(F))
858 Blocks.push_back(&Block);
859
860 for (auto &Block : Blocks) {
861 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
862 if (!BB)
863 continue;
864 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
865 if (!DestBB ||
866 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
867 continue;
868
869 eliminateMostlyEmptyBlock(BB);
870 MadeChange = true;
871 }
872 return MadeChange;
873}
874
875bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
876 BasicBlock *DestBB,
877 bool isPreheader) {
878 // Do not delete loop preheaders if doing so would create a critical edge.
879 // Loop preheaders can be good locations to spill registers. If the
880 // preheader is deleted and we create a critical edge, registers may be
881 // spilled in the loop body instead.
882 if (!DisablePreheaderProtect && isPreheader &&
883 !(BB->getSinglePredecessor() &&
885 return false;
886
887 // Skip merging if the block's successor is also a successor to any callbr
888 // that leads to this block.
889 // FIXME: Is this really needed? Is this a correctness issue?
890 for (BasicBlock *Pred : predecessors(BB)) {
891 if (auto *CBI = dyn_cast<CallBrInst>((Pred)->getTerminator()))
892 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
893 if (DestBB == CBI->getSuccessor(i))
894 return false;
895 }
896
897 // Try to skip merging if the unique predecessor of BB is terminated by a
898 // switch or indirect branch instruction, and BB is used as an incoming block
899 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
900 // add COPY instructions in the predecessor of BB instead of BB (if it is not
901 // merged). Note that the critical edge created by merging such blocks wont be
902 // split in MachineSink because the jump table is not analyzable. By keeping
903 // such empty block (BB), ISel will place COPY instructions in BB, not in the
904 // predecessor of BB.
905 BasicBlock *Pred = BB->getUniquePredecessor();
906 if (!Pred || !(isa<SwitchInst>(Pred->getTerminator()) ||
907 isa<IndirectBrInst>(Pred->getTerminator())))
908 return true;
909
910 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
911 return true;
912
913 // We use a simple cost heuristic which determine skipping merging is
914 // profitable if the cost of skipping merging is less than the cost of
915 // merging : Cost(skipping merging) < Cost(merging BB), where the
916 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
917 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
918 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
919 // Freq(Pred) / Freq(BB) > 2.
920 // Note that if there are multiple empty blocks sharing the same incoming
921 // value for the PHIs in the DestBB, we consider them together. In such
922 // case, Cost(merging BB) will be the sum of their frequencies.
923
924 if (!isa<PHINode>(DestBB->begin()))
925 return true;
926
927 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
928
929 // Find all other incoming blocks from which incoming values of all PHIs in
930 // DestBB are the same as the ones from BB.
931 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
932 if (DestBBPred == BB)
933 continue;
934
935 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
936 return DestPN.getIncomingValueForBlock(BB) ==
937 DestPN.getIncomingValueForBlock(DestBBPred);
938 }))
939 SameIncomingValueBBs.insert(DestBBPred);
940 }
941
942 // See if all BB's incoming values are same as the value from Pred. In this
943 // case, no reason to skip merging because COPYs are expected to be place in
944 // Pred already.
945 if (SameIncomingValueBBs.count(Pred))
946 return true;
947
948 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
949 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
950
951 for (auto *SameValueBB : SameIncomingValueBBs)
952 if (SameValueBB->getUniquePredecessor() == Pred &&
953 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
954 BBFreq += BFI->getBlockFreq(SameValueBB);
955
956 return PredFreq.getFrequency() <=
958}
959
960/// Return true if we can merge BB into DestBB if there is a single
961/// unconditional branch between them, and BB contains no other non-phi
962/// instructions.
963bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
964 const BasicBlock *DestBB) const {
965 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
966 // the successor. If there are more complex condition (e.g. preheaders),
967 // don't mess around with them.
968 for (const PHINode &PN : BB->phis()) {
969 for (const User *U : PN.users()) {
970 const Instruction *UI = cast<Instruction>(U);
971 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
972 return false;
973 // If User is inside DestBB block and it is a PHINode then check
974 // incoming value. If incoming value is not from BB then this is
975 // a complex condition (e.g. preheaders) we want to avoid here.
976 if (UI->getParent() == DestBB) {
977 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
978 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
979 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
980 if (Insn && Insn->getParent() == BB &&
981 Insn->getParent() != UPN->getIncomingBlock(I))
982 return false;
983 }
984 }
985 }
986 }
987
988 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
989 // and DestBB may have conflicting incoming values for the block. If so, we
990 // can't merge the block.
991 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
992 if (!DestBBPN)
993 return true; // no conflict.
994
995 // Collect the preds of BB.
997 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
998 // It is faster to get preds from a PHI than with pred_iterator.
999 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1000 BBPreds.insert(BBPN->getIncomingBlock(i));
1001 } else {
1002 BBPreds.insert(pred_begin(BB), pred_end(BB));
1003 }
1004
1005 // Walk the preds of DestBB.
1006 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1007 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1008 if (BBPreds.count(Pred)) { // Common predecessor?
1009 for (const PHINode &PN : DestBB->phis()) {
1010 const Value *V1 = PN.getIncomingValueForBlock(Pred);
1011 const Value *V2 = PN.getIncomingValueForBlock(BB);
1012
1013 // If V2 is a phi node in BB, look up what the mapped value will be.
1014 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1015 if (V2PN->getParent() == BB)
1016 V2 = V2PN->getIncomingValueForBlock(Pred);
1017
1018 // If there is a conflict, bail out.
1019 if (V1 != V2)
1020 return false;
1021 }
1022 }
1023 }
1024
1025 return true;
1026}
1027
1028/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
1029static void replaceAllUsesWith(Value *Old, Value *New,
1031 bool IsHuge) {
1032 auto *OldI = dyn_cast<Instruction>(Old);
1033 if (OldI) {
1034 for (Value::user_iterator UI = OldI->user_begin(), E = OldI->user_end();
1035 UI != E; ++UI) {
1036 Instruction *User = cast<Instruction>(*UI);
1037 if (IsHuge)
1038 FreshBBs.insert(User->getParent());
1039 }
1040 }
1041 Old->replaceAllUsesWith(New);
1042}
1043
1044/// Eliminate a basic block that has only phi's and an unconditional branch in
1045/// it.
1046void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1047 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1048 BasicBlock *DestBB = BI->getSuccessor(0);
1049
1050 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1051 << *BB << *DestBB);
1052
1053 // If the destination block has a single pred, then this is a trivial edge,
1054 // just collapse it.
1055 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1056 if (SinglePred != DestBB) {
1057 assert(SinglePred == BB &&
1058 "Single predecessor not the same as predecessor");
1059 // Merge DestBB into SinglePred/BB and delete it.
1061 // Note: BB(=SinglePred) will not be deleted on this path.
1062 // DestBB(=its single successor) is the one that was deleted.
1063 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1064
1065 if (IsHugeFunc) {
1066 // Update FreshBBs to optimize the merged BB.
1067 FreshBBs.insert(SinglePred);
1068 FreshBBs.erase(DestBB);
1069 }
1070 return;
1071 }
1072 }
1073
1074 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1075 // to handle the new incoming edges it is about to have.
1076 for (PHINode &PN : DestBB->phis()) {
1077 // Remove the incoming value for BB, and remember it.
1078 Value *InVal = PN.removeIncomingValue(BB, false);
1079
1080 // Two options: either the InVal is a phi node defined in BB or it is some
1081 // value that dominates BB.
1082 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1083 if (InValPhi && InValPhi->getParent() == BB) {
1084 // Add all of the input values of the input PHI as inputs of this phi.
1085 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1086 PN.addIncoming(InValPhi->getIncomingValue(i),
1087 InValPhi->getIncomingBlock(i));
1088 } else {
1089 // Otherwise, add one instance of the dominating value for each edge that
1090 // we will be adding.
1091 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1092 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1093 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1094 } else {
1095 for (BasicBlock *Pred : predecessors(BB))
1096 PN.addIncoming(InVal, Pred);
1097 }
1098 }
1099 }
1100
1101 // The PHIs are now updated, change everything that refers to BB to use
1102 // DestBB and remove BB.
1103 BB->replaceAllUsesWith(DestBB);
1104 BB->eraseFromParent();
1105 ++NumBlocksElim;
1106
1107 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1108}
1109
1110// Computes a map of base pointer relocation instructions to corresponding
1111// derived pointer relocation instructions given a vector of all relocate calls
1113 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1115 &RelocateInstMap) {
1116 // Collect information in two maps: one primarily for locating the base object
1117 // while filling the second map; the second map is the final structure holding
1118 // a mapping between Base and corresponding Derived relocate calls
1120 for (auto *ThisRelocate : AllRelocateCalls) {
1121 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1122 ThisRelocate->getDerivedPtrIndex());
1123 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1124 }
1125 for (auto &Item : RelocateIdxMap) {
1126 std::pair<unsigned, unsigned> Key = Item.first;
1127 if (Key.first == Key.second)
1128 // Base relocation: nothing to insert
1129 continue;
1130
1131 GCRelocateInst *I = Item.second;
1132 auto BaseKey = std::make_pair(Key.first, Key.first);
1133
1134 // We're iterating over RelocateIdxMap so we cannot modify it.
1135 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1136 if (MaybeBase == RelocateIdxMap.end())
1137 // TODO: We might want to insert a new base object relocate and gep off
1138 // that, if there are enough derived object relocates.
1139 continue;
1140
1141 RelocateInstMap[MaybeBase->second].push_back(I);
1142 }
1143}
1144
1145// Accepts a GEP and extracts the operands into a vector provided they're all
1146// small integer constants
1148 SmallVectorImpl<Value *> &OffsetV) {
1149 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1150 // Only accept small constant integer operands
1151 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1152 if (!Op || Op->getZExtValue() > 20)
1153 return false;
1154 }
1155
1156 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1157 OffsetV.push_back(GEP->getOperand(i));
1158 return true;
1159}
1160
1161// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1162// replace, computes a replacement, and affects it.
1163static bool
1166 bool MadeChange = false;
1167 // We must ensure the relocation of derived pointer is defined after
1168 // relocation of base pointer. If we find a relocation corresponding to base
1169 // defined earlier than relocation of base then we move relocation of base
1170 // right before found relocation. We consider only relocation in the same
1171 // basic block as relocation of base. Relocations from other basic block will
1172 // be skipped by optimization and we do not care about them.
1173 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1174 &*R != RelocatedBase; ++R)
1175 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1176 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1177 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1178 RelocatedBase->moveBefore(RI);
1179 break;
1180 }
1181
1182 for (GCRelocateInst *ToReplace : Targets) {
1183 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1184 "Not relocating a derived object of the original base object");
1185 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1186 // A duplicate relocate call. TODO: coalesce duplicates.
1187 continue;
1188 }
1189
1190 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1191 // Base and derived relocates are in different basic blocks.
1192 // In this case transform is only valid when base dominates derived
1193 // relocate. However it would be too expensive to check dominance
1194 // for each such relocate, so we skip the whole transformation.
1195 continue;
1196 }
1197
1198 Value *Base = ToReplace->getBasePtr();
1199 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1200 if (!Derived || Derived->getPointerOperand() != Base)
1201 continue;
1202
1204 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1205 continue;
1206
1207 // Create a Builder and replace the target callsite with a gep
1208 assert(RelocatedBase->getNextNode() &&
1209 "Should always have one since it's not a terminator");
1210
1211 // Insert after RelocatedBase
1212 IRBuilder<> Builder(RelocatedBase->getNextNode());
1213 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1214
1215 // If gc_relocate does not match the actual type, cast it to the right type.
1216 // In theory, there must be a bitcast after gc_relocate if the type does not
1217 // match, and we should reuse it to get the derived pointer. But it could be
1218 // cases like this:
1219 // bb1:
1220 // ...
1221 // %g1 = call coldcc i8 addrspace(1)*
1222 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1223 //
1224 // bb2:
1225 // ...
1226 // %g2 = call coldcc i8 addrspace(1)*
1227 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1228 //
1229 // merge:
1230 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1231 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1232 //
1233 // In this case, we can not find the bitcast any more. So we insert a new
1234 // bitcast no matter there is already one or not. In this way, we can handle
1235 // all cases, and the extra bitcast should be optimized away in later
1236 // passes.
1237 Value *ActualRelocatedBase = RelocatedBase;
1238 if (RelocatedBase->getType() != Base->getType()) {
1239 ActualRelocatedBase =
1240 Builder.CreateBitCast(RelocatedBase, Base->getType());
1241 }
1242 Value *Replacement =
1243 Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
1244 ArrayRef(OffsetV));
1245 Replacement->takeName(ToReplace);
1246 // If the newly generated derived pointer's type does not match the original
1247 // derived pointer's type, cast the new derived pointer to match it. Same
1248 // reasoning as above.
1249 Value *ActualReplacement = Replacement;
1250 if (Replacement->getType() != ToReplace->getType()) {
1251 ActualReplacement =
1252 Builder.CreateBitCast(Replacement, ToReplace->getType());
1253 }
1254 ToReplace->replaceAllUsesWith(ActualReplacement);
1255 ToReplace->eraseFromParent();
1256
1257 MadeChange = true;
1258 }
1259 return MadeChange;
1260}
1261
1262// Turns this:
1263//
1264// %base = ...
1265// %ptr = gep %base + 15
1266// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1267// %base' = relocate(%tok, i32 4, i32 4)
1268// %ptr' = relocate(%tok, i32 4, i32 5)
1269// %val = load %ptr'
1270//
1271// into this:
1272//
1273// %base = ...
1274// %ptr = gep %base + 15
1275// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1276// %base' = gc.relocate(%tok, i32 4, i32 4)
1277// %ptr' = gep %base' + 15
1278// %val = load %ptr'
1279bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1280 bool MadeChange = false;
1281 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1282 for (auto *U : I.users())
1283 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1284 // Collect all the relocate calls associated with a statepoint
1285 AllRelocateCalls.push_back(Relocate);
1286
1287 // We need at least one base pointer relocation + one derived pointer
1288 // relocation to mangle
1289 if (AllRelocateCalls.size() < 2)
1290 return false;
1291
1292 // RelocateInstMap is a mapping from the base relocate instruction to the
1293 // corresponding derived relocate instructions
1295 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1296 if (RelocateInstMap.empty())
1297 return false;
1298
1299 for (auto &Item : RelocateInstMap)
1300 // Item.first is the RelocatedBase to offset against
1301 // Item.second is the vector of Targets to replace
1302 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1303 return MadeChange;
1304}
1305
1306/// Sink the specified cast instruction into its user blocks.
1307static bool SinkCast(CastInst *CI) {
1308 BasicBlock *DefBB = CI->getParent();
1309
1310 /// InsertedCasts - Only insert a cast in each block once.
1312
1313 bool MadeChange = false;
1314 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1315 UI != E;) {
1316 Use &TheUse = UI.getUse();
1317 Instruction *User = cast<Instruction>(*UI);
1318
1319 // Figure out which BB this cast is used in. For PHI's this is the
1320 // appropriate predecessor block.
1321 BasicBlock *UserBB = User->getParent();
1322 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1323 UserBB = PN->getIncomingBlock(TheUse);
1324 }
1325
1326 // Preincrement use iterator so we don't invalidate it.
1327 ++UI;
1328
1329 // The first insertion point of a block containing an EH pad is after the
1330 // pad. If the pad is the user, we cannot sink the cast past the pad.
1331 if (User->isEHPad())
1332 continue;
1333
1334 // If the block selected to receive the cast is an EH pad that does not
1335 // allow non-PHI instructions before the terminator, we can't sink the
1336 // cast.
1337 if (UserBB->getTerminator()->isEHPad())
1338 continue;
1339
1340 // If this user is in the same block as the cast, don't change the cast.
1341 if (UserBB == DefBB)
1342 continue;
1343
1344 // If we have already inserted a cast into this block, use it.
1345 CastInst *&InsertedCast = InsertedCasts[UserBB];
1346
1347 if (!InsertedCast) {
1348 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1349 assert(InsertPt != UserBB->end());
1350 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1351 CI->getType(), "", &*InsertPt);
1352 InsertedCast->setDebugLoc(CI->getDebugLoc());
1353 }
1354
1355 // Replace a use of the cast with a use of the new cast.
1356 TheUse = InsertedCast;
1357 MadeChange = true;
1358 ++NumCastUses;
1359 }
1360
1361 // If we removed all uses, nuke the cast.
1362 if (CI->use_empty()) {
1363 salvageDebugInfo(*CI);
1364 CI->eraseFromParent();
1365 MadeChange = true;
1366 }
1367
1368 return MadeChange;
1369}
1370
1371/// If the specified cast instruction is a noop copy (e.g. it's casting from
1372/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1373/// reduce the number of virtual registers that must be created and coalesced.
1374///
1375/// Return true if any changes are made.
1377 const DataLayout &DL) {
1378 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1379 // than sinking only nop casts, but is helpful on some platforms.
1380 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1381 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
1382 ASC->getDestAddressSpace()))
1383 return false;
1384 }
1385
1386 // If this is a noop copy,
1387 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1388 EVT DstVT = TLI.getValueType(DL, CI->getType());
1389
1390 // This is an fp<->int conversion?
1391 if (SrcVT.isInteger() != DstVT.isInteger())
1392 return false;
1393
1394 // If this is an extension, it will be a zero or sign extension, which
1395 // isn't a noop.
1396 if (SrcVT.bitsLT(DstVT))
1397 return false;
1398
1399 // If these values will be promoted, find out what they will be promoted
1400 // to. This helps us consider truncates on PPC as noop copies when they
1401 // are.
1402 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1403 TargetLowering::TypePromoteInteger)
1404 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1405 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1406 TargetLowering::TypePromoteInteger)
1407 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1408
1409 // If, after promotion, these are the same types, this is a noop copy.
1410 if (SrcVT != DstVT)
1411 return false;
1412
1413 return SinkCast(CI);
1414}
1415
1416// Match a simple increment by constant operation. Note that if a sub is
1417// matched, the step is negated (as if the step had been canonicalized to
1418// an add, even though we leave the instruction alone.)
1419bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1420 Constant *&Step) {
1421 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1422 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::uadd_with_overflow>(
1423 m_Instruction(LHS), m_Constant(Step)))))
1424 return true;
1425 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1426 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
1427 m_Instruction(LHS), m_Constant(Step))))) {
1428 Step = ConstantExpr::getNeg(Step);
1429 return true;
1430 }
1431 return false;
1432}
1433
1434/// If given \p PN is an inductive variable with value IVInc coming from the
1435/// backedge, and on each iteration it gets increased by Step, return pair
1436/// <IVInc, Step>. Otherwise, return std::nullopt.
1437static std::optional<std::pair<Instruction *, Constant *>>
1438getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1439 const Loop *L = LI->getLoopFor(PN->getParent());
1440 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1441 return std::nullopt;
1442 auto *IVInc =
1443 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1444 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1445 return std::nullopt;
1446 Instruction *LHS = nullptr;
1447 Constant *Step = nullptr;
1448 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1449 return std::make_pair(IVInc, Step);
1450 return std::nullopt;
1451}
1452
1453static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1454 auto *I = dyn_cast<Instruction>(V);
1455 if (!I)
1456 return false;
1457 Instruction *LHS = nullptr;
1458 Constant *Step = nullptr;
1459 if (!matchIncrement(I, LHS, Step))
1460 return false;
1461 if (auto *PN = dyn_cast<PHINode>(LHS))
1462 if (auto IVInc = getIVIncrement(PN, LI))
1463 return IVInc->first == I;
1464 return false;
1465}
1466
1467bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1468 Value *Arg0, Value *Arg1,
1469 CmpInst *Cmp,
1470 Intrinsic::ID IID) {
1471 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1472 if (!isIVIncrement(BO, LI))
1473 return false;
1474 const Loop *L = LI->getLoopFor(BO->getParent());
1475 assert(L && "L should not be null after isIVIncrement()");
1476 // Do not risk on moving increment into a child loop.
1477 if (LI->getLoopFor(Cmp->getParent()) != L)
1478 return false;
1479
1480 // Finally, we need to ensure that the insert point will dominate all
1481 // existing uses of the increment.
1482
1483 auto &DT = getDT(*BO->getParent()->getParent());
1484 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1485 // If we're moving up the dom tree, all uses are trivially dominated.
1486 // (This is the common case for code produced by LSR.)
1487 return true;
1488
1489 // Otherwise, special case the single use in the phi recurrence.
1490 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1491 };
1492 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1493 // We used to use a dominator tree here to allow multi-block optimization.
1494 // But that was problematic because:
1495 // 1. It could cause a perf regression by hoisting the math op into the
1496 // critical path.
1497 // 2. It could cause a perf regression by creating a value that was live
1498 // across multiple blocks and increasing register pressure.
1499 // 3. Use of a dominator tree could cause large compile-time regression.
1500 // This is because we recompute the DT on every change in the main CGP
1501 // run-loop. The recomputing is probably unnecessary in many cases, so if
1502 // that was fixed, using a DT here would be ok.
1503 //
1504 // There is one important particular case we still want to handle: if BO is
1505 // the IV increment. Important properties that make it profitable:
1506 // - We can speculate IV increment anywhere in the loop (as long as the
1507 // indvar Phi is its only user);
1508 // - Upon computing Cmp, we effectively compute something equivalent to the
1509 // IV increment (despite it loops differently in the IR). So moving it up
1510 // to the cmp point does not really increase register pressure.
1511 return false;
1512 }
1513
1514 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1515 if (BO->getOpcode() == Instruction::Add &&
1516 IID == Intrinsic::usub_with_overflow) {
1517 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1518 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
1519 }
1520
1521 // Insert at the first instruction of the pair.
1522 Instruction *InsertPt = nullptr;
1523 for (Instruction &Iter : *Cmp->getParent()) {
1524 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1525 // the overflow intrinsic are defined.
1526 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1527 InsertPt = &Iter;
1528 break;
1529 }
1530 }
1531 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1532
1533 IRBuilder<> Builder(InsertPt);
1534 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1535 if (BO->getOpcode() != Instruction::Xor) {
1536 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1537 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1538 } else
1539 assert(BO->hasOneUse() &&
1540 "Patterns with XOr should use the BO only in the compare");
1541 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1542 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1543 Cmp->eraseFromParent();
1544 BO->eraseFromParent();
1545 return true;
1546}
1547
1548/// Match special-case patterns that check for unsigned add overflow.
1550 BinaryOperator *&Add) {
1551 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1552 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1553 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1554
1555 // We are not expecting non-canonical/degenerate code. Just bail out.
1556 if (isa<Constant>(A))
1557 return false;
1558
1559 ICmpInst::Predicate Pred = Cmp->getPredicate();
1560 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1561 B = ConstantInt::get(B->getType(), 1);
1562 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1563 B = ConstantInt::get(B->getType(), -1);
1564 else
1565 return false;
1566
1567 // Check the users of the variable operand of the compare looking for an add
1568 // with the adjusted constant.
1569 for (User *U : A->users()) {
1570 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1571 Add = cast<BinaryOperator>(U);
1572 return true;
1573 }
1574 }
1575 return false;
1576}
1577
1578/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1579/// intrinsic. Return true if any changes were made.
1580bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1581 ModifyDT &ModifiedDT) {
1582 bool EdgeCase = false;
1583 Value *A, *B;
1585 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1587 return false;
1588 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1589 A = Add->getOperand(0);
1590 B = Add->getOperand(1);
1591 EdgeCase = true;
1592 }
1593
1595 TLI->getValueType(*DL, Add->getType()),
1596 Add->hasNUsesOrMore(EdgeCase ? 1 : 2)))
1597 return false;
1598
1599 // We don't want to move around uses of condition values this late, so we
1600 // check if it is legal to create the call to the intrinsic in the basic
1601 // block containing the icmp.
1602 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1603 return false;
1604
1605 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1606 Intrinsic::uadd_with_overflow))
1607 return false;
1608
1609 // Reset callers - do not crash by iterating over a dead instruction.
1610 ModifiedDT = ModifyDT::ModifyInstDT;
1611 return true;
1612}
1613
1614bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1615 ModifyDT &ModifiedDT) {
1616 // We are not expecting non-canonical/degenerate code. Just bail out.
1617 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1618 if (isa<Constant>(A) && isa<Constant>(B))
1619 return false;
1620
1621 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1622 ICmpInst::Predicate Pred = Cmp->getPredicate();
1623 if (Pred == ICmpInst::ICMP_UGT) {
1624 std::swap(A, B);
1625 Pred = ICmpInst::ICMP_ULT;
1626 }
1627 // Convert special-case: (A == 0) is the same as (A u< 1).
1628 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1629 B = ConstantInt::get(B->getType(), 1);
1630 Pred = ICmpInst::ICMP_ULT;
1631 }
1632 // Convert special-case: (A != 0) is the same as (0 u< A).
1633 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1634 std::swap(A, B);
1635 Pred = ICmpInst::ICMP_ULT;
1636 }
1637 if (Pred != ICmpInst::ICMP_ULT)
1638 return false;
1639
1640 // Walk the users of a variable operand of a compare looking for a subtract or
1641 // add with that same operand. Also match the 2nd operand of the compare to
1642 // the add/sub, but that may be a negated constant operand of an add.
1643 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1644 BinaryOperator *Sub = nullptr;
1645 for (User *U : CmpVariableOperand->users()) {
1646 // A - B, A u< B --> usubo(A, B)
1647 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1648 Sub = cast<BinaryOperator>(U);
1649 break;
1650 }
1651
1652 // A + (-C), A u< C (canonicalized form of (sub A, C))
1653 const APInt *CmpC, *AddC;
1654 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1655 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1656 Sub = cast<BinaryOperator>(U);
1657 break;
1658 }
1659 }
1660 if (!Sub)
1661 return false;
1662
1664 TLI->getValueType(*DL, Sub->getType()),
1665 Sub->hasNUsesOrMore(1)))
1666 return false;
1667
1668 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1669 Cmp, Intrinsic::usub_with_overflow))
1670 return false;
1671
1672 // Reset callers - do not crash by iterating over a dead instruction.
1673 ModifiedDT = ModifyDT::ModifyInstDT;
1674 return true;
1675}
1676
1677/// Sink the given CmpInst into user blocks to reduce the number of virtual
1678/// registers that must be created and coalesced. This is a clear win except on
1679/// targets with multiple condition code registers (PowerPC), where it might
1680/// lose; some adjustment may be wanted there.
1681///
1682/// Return true if any changes are made.
1683static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
1685 return false;
1686
1687 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1688 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1689 return false;
1690
1691 // Only insert a cmp in each block once.
1693
1694 bool MadeChange = false;
1695 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1696 UI != E;) {
1697 Use &TheUse = UI.getUse();
1698 Instruction *User = cast<Instruction>(*UI);
1699
1700 // Preincrement use iterator so we don't invalidate it.
1701 ++UI;
1702
1703 // Don't bother for PHI nodes.
1704 if (isa<PHINode>(User))
1705 continue;
1706
1707 // Figure out which BB this cmp is used in.
1708 BasicBlock *UserBB = User->getParent();
1709 BasicBlock *DefBB = Cmp->getParent();
1710
1711 // If this user is in the same block as the cmp, don't change the cmp.
1712 if (UserBB == DefBB)
1713 continue;
1714
1715 // If we have already inserted a cmp into this block, use it.
1716 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1717
1718 if (!InsertedCmp) {
1719 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1720 assert(InsertPt != UserBB->end());
1721 InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1722 Cmp->getOperand(0), Cmp->getOperand(1), "",
1723 &*InsertPt);
1724 // Propagate the debug info.
1725 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1726 }
1727
1728 // Replace a use of the cmp with a use of the new cmp.
1729 TheUse = InsertedCmp;
1730 MadeChange = true;
1731 ++NumCmpUses;
1732 }
1733
1734 // If we removed all uses, nuke the cmp.
1735 if (Cmp->use_empty()) {
1736 Cmp->eraseFromParent();
1737 MadeChange = true;
1738 }
1739
1740 return MadeChange;
1741}
1742
1743/// For pattern like:
1744///
1745/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1746/// ...
1747/// DomBB:
1748/// ...
1749/// br DomCond, TrueBB, CmpBB
1750/// CmpBB: (with DomBB being the single predecessor)
1751/// ...
1752/// Cmp = icmp eq CmpOp0, CmpOp1
1753/// ...
1754///
1755/// It would use two comparison on targets that lowering of icmp sgt/slt is
1756/// different from lowering of icmp eq (PowerPC). This function try to convert
1757/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1758/// After that, DomCond and Cmp can use the same comparison so reduce one
1759/// comparison.
1760///
1761/// Return true if any changes are made.
1763 const TargetLowering &TLI) {
1765 return false;
1766
1767 ICmpInst::Predicate Pred = Cmp->getPredicate();
1768 if (Pred != ICmpInst::ICMP_EQ)
1769 return false;
1770
1771 // If icmp eq has users other than BranchInst and SelectInst, converting it to
1772 // icmp slt/sgt would introduce more redundant LLVM IR.
1773 for (User *U : Cmp->users()) {
1774 if (isa<BranchInst>(U))
1775 continue;
1776 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1777 continue;
1778 return false;
1779 }
1780
1781 // This is a cheap/incomplete check for dominance - just match a single
1782 // predecessor with a conditional branch.
1783 BasicBlock *CmpBB = Cmp->getParent();
1784 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1785 if (!DomBB)
1786 return false;
1787
1788 // We want to ensure that the only way control gets to the comparison of
1789 // interest is that a less/greater than comparison on the same operands is
1790 // false.
1791 Value *DomCond;
1792 BasicBlock *TrueBB, *FalseBB;
1793 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1794 return false;
1795 if (CmpBB != FalseBB)
1796 return false;
1797
1798 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1799 ICmpInst::Predicate DomPred;
1800 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
1801 return false;
1802 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
1803 return false;
1804
1805 // Convert the equality comparison to the opposite of the dominating
1806 // comparison and swap the direction for all branch/select users.
1807 // We have conceptually converted:
1808 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
1809 // to
1810 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
1811 // And similarly for branches.
1812 for (User *U : Cmp->users()) {
1813 if (auto *BI = dyn_cast<BranchInst>(U)) {
1814 assert(BI->isConditional() && "Must be conditional");
1815 BI->swapSuccessors();
1816 continue;
1817 }
1818 if (auto *SI = dyn_cast<SelectInst>(U)) {
1819 // Swap operands
1820 SI->swapValues();
1821 SI->swapProfMetadata();
1822 continue;
1823 }
1824 llvm_unreachable("Must be a branch or a select");
1825 }
1826 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
1827 return true;
1828}
1829
1830bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
1831 if (sinkCmpExpression(Cmp, *TLI))
1832 return true;
1833
1834 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
1835 return true;
1836
1837 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
1838 return true;
1839
1840 if (foldICmpWithDominatingICmp(Cmp, *TLI))
1841 return true;
1842
1843 return false;
1844}
1845
1846/// Duplicate and sink the given 'and' instruction into user blocks where it is
1847/// used in a compare to allow isel to generate better code for targets where
1848/// this operation can be combined.
1849///
1850/// Return true if any changes are made.
1852 SetOfInstrs &InsertedInsts) {
1853 // Double-check that we're not trying to optimize an instruction that was
1854 // already optimized by some other part of this pass.
1855 assert(!InsertedInsts.count(AndI) &&
1856 "Attempting to optimize already optimized and instruction");
1857 (void)InsertedInsts;
1858
1859 // Nothing to do for single use in same basic block.
1860 if (AndI->hasOneUse() &&
1861 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1862 return false;
1863
1864 // Try to avoid cases where sinking/duplicating is likely to increase register
1865 // pressure.
1866 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1867 !isa<ConstantInt>(AndI->getOperand(1)) &&
1868 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1869 return false;
1870
1871 for (auto *U : AndI->users()) {
1872 Instruction *User = cast<Instruction>(U);
1873
1874 // Only sink 'and' feeding icmp with 0.
1875 if (!isa<ICmpInst>(User))
1876 return false;
1877
1878 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1879 if (!CmpC || !CmpC->isZero())
1880 return false;
1881 }
1882
1883 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1884 return false;
1885
1886 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1887 LLVM_DEBUG(AndI->getParent()->dump());
1888
1889 // Push the 'and' into the same block as the icmp 0. There should only be
1890 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1891 // others, so we don't need to keep track of which BBs we insert into.
1892 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1893 UI != E;) {
1894 Use &TheUse = UI.getUse();
1895 Instruction *User = cast<Instruction>(*UI);
1896
1897 // Preincrement use iterator so we don't invalidate it.
1898 ++UI;
1899
1900 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1901
1902 // Keep the 'and' in the same place if the use is already in the same block.
1903 Instruction *InsertPt =
1904 User->getParent() == AndI->getParent() ? AndI : User;
1905 Instruction *InsertedAnd =
1906 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1907 AndI->getOperand(1), "", InsertPt);
1908 // Propagate the debug info.
1909 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1910
1911 // Replace a use of the 'and' with a use of the new 'and'.
1912 TheUse = InsertedAnd;
1913 ++NumAndUses;
1914 LLVM_DEBUG(User->getParent()->dump());
1915 }
1916
1917 // We removed all uses, nuke the and.
1918 AndI->eraseFromParent();
1919 return true;
1920}
1921
1922/// Check if the candidates could be combined with a shift instruction, which
1923/// includes:
1924/// 1. Truncate instruction
1925/// 2. And instruction and the imm is a mask of the low bits:
1926/// imm & (imm+1) == 0
1928 if (!isa<TruncInst>(User)) {
1929 if (User->getOpcode() != Instruction::And ||
1930 !isa<ConstantInt>(User->getOperand(1)))
1931 return false;
1932
1933 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1934
1935 if ((Cimm & (Cimm + 1)).getBoolValue())
1936 return false;
1937 }
1938 return true;
1939}
1940
1941/// Sink both shift and truncate instruction to the use of truncate's BB.
1942static bool
1945 const TargetLowering &TLI, const DataLayout &DL) {
1946 BasicBlock *UserBB = User->getParent();
1948 auto *TruncI = cast<TruncInst>(User);
1949 bool MadeChange = false;
1950
1951 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1952 TruncE = TruncI->user_end();
1953 TruncUI != TruncE;) {
1954
1955 Use &TruncTheUse = TruncUI.getUse();
1956 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1957 // Preincrement use iterator so we don't invalidate it.
1958
1959 ++TruncUI;
1960
1961 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1962 if (!ISDOpcode)
1963 continue;
1964
1965 // If the use is actually a legal node, there will not be an
1966 // implicit truncate.
1967 // FIXME: always querying the result type is just an
1968 // approximation; some nodes' legality is determined by the
1969 // operand or other means. There's no good way to find out though.
1971 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1972 continue;
1973
1974 // Don't bother for PHI nodes.
1975 if (isa<PHINode>(TruncUser))
1976 continue;
1977
1978 BasicBlock *TruncUserBB = TruncUser->getParent();
1979
1980 if (UserBB == TruncUserBB)
1981 continue;
1982
1983 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1984 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1985
1986 if (!InsertedShift && !InsertedTrunc) {
1987 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1988 assert(InsertPt != TruncUserBB->end());
1989 // Sink the shift
1990 if (ShiftI->getOpcode() == Instruction::AShr)
1991 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1992 "", &*InsertPt);
1993 else
1994 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1995 "", &*InsertPt);
1996 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
1997
1998 // Sink the trunc
1999 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2000 TruncInsertPt++;
2001 assert(TruncInsertPt != TruncUserBB->end());
2002
2003 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2004 TruncI->getType(), "", &*TruncInsertPt);
2005 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2006
2007 MadeChange = true;
2008
2009 TruncTheUse = InsertedTrunc;
2010 }
2011 }
2012 return MadeChange;
2013}
2014
2015/// Sink the shift *right* instruction into user blocks if the uses could
2016/// potentially be combined with this shift instruction and generate BitExtract
2017/// instruction. It will only be applied if the architecture supports BitExtract
2018/// instruction. Here is an example:
2019/// BB1:
2020/// %x.extract.shift = lshr i64 %arg1, 32
2021/// BB2:
2022/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2023/// ==>
2024///
2025/// BB2:
2026/// %x.extract.shift.1 = lshr i64 %arg1, 32
2027/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2028///
2029/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2030/// instruction.
2031/// Return true if any changes are made.
2033 const TargetLowering &TLI,
2034 const DataLayout &DL) {
2035 BasicBlock *DefBB = ShiftI->getParent();
2036
2037 /// Only insert instructions in each block once.
2039
2040 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2041
2042 bool MadeChange = false;
2043 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2044 UI != E;) {
2045 Use &TheUse = UI.getUse();
2046 Instruction *User = cast<Instruction>(*UI);
2047 // Preincrement use iterator so we don't invalidate it.
2048 ++UI;
2049
2050 // Don't bother for PHI nodes.
2051 if (isa<PHINode>(User))
2052 continue;
2053
2055 continue;
2056
2057 BasicBlock *UserBB = User->getParent();
2058
2059 if (UserBB == DefBB) {
2060 // If the shift and truncate instruction are in the same BB. The use of
2061 // the truncate(TruncUse) may still introduce another truncate if not
2062 // legal. In this case, we would like to sink both shift and truncate
2063 // instruction to the BB of TruncUse.
2064 // for example:
2065 // BB1:
2066 // i64 shift.result = lshr i64 opnd, imm
2067 // trunc.result = trunc shift.result to i16
2068 //
2069 // BB2:
2070 // ----> We will have an implicit truncate here if the architecture does
2071 // not have i16 compare.
2072 // cmp i16 trunc.result, opnd2
2073 //
2074 if (isa<TruncInst>(User) &&
2075 shiftIsLegal
2076 // If the type of the truncate is legal, no truncate will be
2077 // introduced in other basic blocks.
2078 && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2079 MadeChange =
2080 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2081
2082 continue;
2083 }
2084 // If we have already inserted a shift into this block, use it.
2085 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2086
2087 if (!InsertedShift) {
2088 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2089 assert(InsertPt != UserBB->end());
2090
2091 if (ShiftI->getOpcode() == Instruction::AShr)
2092 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2093 "", &*InsertPt);
2094 else
2095 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2096 "", &*InsertPt);
2097 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2098
2099 MadeChange = true;
2100 }
2101
2102 // Replace a use of the shift with a use of the new shift.
2103 TheUse = InsertedShift;
2104 }
2105
2106 // If we removed all uses, or there are none, nuke the shift.
2107 if (ShiftI->use_empty()) {
2108 salvageDebugInfo(*ShiftI);
2109 ShiftI->eraseFromParent();
2110 MadeChange = true;
2111 }
2112
2113 return MadeChange;
2114}
2115
2116/// If counting leading or trailing zeros is an expensive operation and a zero
2117/// input is defined, add a check for zero to avoid calling the intrinsic.
2118///
2119/// We want to transform:
2120/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2121///
2122/// into:
2123/// entry:
2124/// %cmpz = icmp eq i64 %A, 0
2125/// br i1 %cmpz, label %cond.end, label %cond.false
2126/// cond.false:
2127/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2128/// br label %cond.end
2129/// cond.end:
2130/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2131///
2132/// If the transform is performed, return true and set ModifiedDT to true.
2133static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2134 const TargetLowering *TLI,
2135 const DataLayout *DL, ModifyDT &ModifiedDT,
2137 bool IsHugeFunc) {
2138 // If a zero input is undefined, it doesn't make sense to despeculate that.
2139 if (match(CountZeros->getOperand(1), m_One()))
2140 return false;
2141
2142 // If it's cheap to speculate, there's nothing to do.
2143 Type *Ty = CountZeros->getType();
2144 auto IntrinsicID = CountZeros->getIntrinsicID();
2145 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2146 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2147 return false;
2148
2149 // Only handle legal scalar cases. Anything else requires too much work.
2150 unsigned SizeInBits = Ty->getScalarSizeInBits();
2151 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
2152 return false;
2153
2154 // Bail if the value is never zero.
2155 Use &Op = CountZeros->getOperandUse(0);
2156 if (isKnownNonZero(Op, *DL))
2157 return false;
2158
2159 // The intrinsic will be sunk behind a compare against zero and branch.
2160 BasicBlock *StartBlock = CountZeros->getParent();
2161 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2162 if (IsHugeFunc)
2163 FreshBBs.insert(CallBlock);
2164
2165 // Create another block after the count zero intrinsic. A PHI will be added
2166 // in this block to select the result of the intrinsic or the bit-width
2167 // constant if the input to the intrinsic is zero.
2168 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2169 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2170 if (IsHugeFunc)
2171 FreshBBs.insert(EndBlock);
2172
2173 // Set up a builder to create a compare, conditional branch, and PHI.
2174 IRBuilder<> Builder(CountZeros->getContext());
2175 Builder.SetInsertPoint(StartBlock->getTerminator());
2176 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2177
2178 // Replace the unconditional branch that was created by the first split with
2179 // a compare against zero and a conditional branch.
2180 Value *Zero = Constant::getNullValue(Ty);
2181 // Avoid introducing branch on poison. This also replaces the ctz operand.
2183 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2184 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2185 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2186 StartBlock->getTerminator()->eraseFromParent();
2187
2188 // Create a PHI in the end block to select either the output of the intrinsic
2189 // or the bit width of the operand.
2190 Builder.SetInsertPoint(&EndBlock->front());
2191 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2192 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2193 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2194 PN->addIncoming(BitWidth, StartBlock);
2195 PN->addIncoming(CountZeros, CallBlock);
2196
2197 // We are explicitly handling the zero case, so we can set the intrinsic's
2198 // undefined zero argument to 'true'. This will also prevent reprocessing the
2199 // intrinsic; we only despeculate when a zero input is defined.
2200 CountZeros->setArgOperand(1, Builder.getTrue());
2201 ModifiedDT = ModifyDT::ModifyBBDT;
2202 return true;
2203}
2204
2205bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2206 BasicBlock *BB = CI->getParent();
2207
2208 // Lower inline assembly if we can.
2209 // If we found an inline asm expession, and if the target knows how to
2210 // lower it to normal LLVM code, do so now.
2211 if (CI->isInlineAsm()) {
2212 if (TLI->ExpandInlineAsm(CI)) {
2213 // Avoid invalidating the iterator.
2214 CurInstIterator = BB->begin();
2215 // Avoid processing instructions out of order, which could cause
2216 // reuse before a value is defined.
2217 SunkAddrs.clear();
2218 return true;
2219 }
2220 // Sink address computing for memory operands into the block.
2221 if (optimizeInlineAsmInst(CI))
2222 return true;
2223 }
2224
2225 // Align the pointer arguments to this call if the target thinks it's a good
2226 // idea
2227 unsigned MinSize;
2228 Align PrefAlign;
2229 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2230 for (auto &Arg : CI->args()) {
2231 // We want to align both objects whose address is used directly and
2232 // objects whose address is used in casts and GEPs, though it only makes
2233 // sense for GEPs if the offset is a multiple of the desired alignment and
2234 // if size - offset meets the size threshold.
2235 if (!Arg->getType()->isPointerTy())
2236 continue;
2237 APInt Offset(DL->getIndexSizeInBits(
2238 cast<PointerType>(Arg->getType())->getAddressSpace()),
2239 0);
2240 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2241 uint64_t Offset2 = Offset.getLimitedValue();
2242 if (!isAligned(PrefAlign, Offset2))
2243 continue;
2244 AllocaInst *AI;
2245 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign &&
2246 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2247 AI->setAlignment(PrefAlign);
2248 // Global variables can only be aligned if they are defined in this
2249 // object (i.e. they are uniquely initialized in this object), and
2250 // over-aligning global variables that have an explicit section is
2251 // forbidden.
2252 GlobalVariable *GV;
2253 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2254 GV->getPointerAlignment(*DL) < PrefAlign &&
2255 DL->getTypeAllocSize(GV->getValueType()) >= MinSize + Offset2)
2256 GV->setAlignment(PrefAlign);
2257 }
2258 }
2259 // If this is a memcpy (or similar) then we may be able to improve the
2260 // alignment.
2261 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2262 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2263 MaybeAlign MIDestAlign = MI->getDestAlign();
2264 if (!MIDestAlign || DestAlign > *MIDestAlign)
2265 MI->setDestAlignment(DestAlign);
2266 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2267 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2268 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2269 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2270 MTI->setSourceAlignment(SrcAlign);
2271 }
2272 }
2273
2274 // If we have a cold call site, try to sink addressing computation into the
2275 // cold block. This interacts with our handling for loads and stores to
2276 // ensure that we can fold all uses of a potential addressing computation
2277 // into their uses. TODO: generalize this to work over profiling data
2278 if (CI->hasFnAttr(Attribute::Cold) && !OptSize &&
2279 !llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
2280 for (auto &Arg : CI->args()) {
2281 if (!Arg->getType()->isPointerTy())
2282 continue;
2283 unsigned AS = Arg->getType()->getPointerAddressSpace();
2284 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2285 return true;
2286 }
2287
2288 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2289 if (II) {
2290 switch (II->getIntrinsicID()) {
2291 default:
2292 break;
2293 case Intrinsic::assume:
2294 llvm_unreachable("llvm.assume should have been removed already");
2295 case Intrinsic::experimental_widenable_condition: {
2296 // Give up on future widening oppurtunties so that we can fold away dead
2297 // paths and merge blocks before going into block-local instruction
2298 // selection.
2299 if (II->use_empty()) {
2300 II->eraseFromParent();
2301 return true;
2302 }
2303 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2304 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2305 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2306 });
2307 return true;
2308 }
2309 case Intrinsic::objectsize:
2310 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2311 case Intrinsic::is_constant:
2312 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2313 case Intrinsic::aarch64_stlxr:
2314 case Intrinsic::aarch64_stxr: {
2315 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2316 if (!ExtVal || !ExtVal->hasOneUse() ||
2317 ExtVal->getParent() == CI->getParent())
2318 return false;
2319 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2320 ExtVal->moveBefore(CI);
2321 // Mark this instruction as "inserted by CGP", so that other
2322 // optimizations don't touch it.
2323 InsertedInsts.insert(ExtVal);
2324 return true;
2325 }
2326
2327 case Intrinsic::launder_invariant_group:
2328 case Intrinsic::strip_invariant_group: {
2329 Value *ArgVal = II->getArgOperand(0);
2330 auto it = LargeOffsetGEPMap.find(II);
2331 if (it != LargeOffsetGEPMap.end()) {
2332 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2333 // Make sure not to have to deal with iterator invalidation
2334 // after possibly adding ArgVal to LargeOffsetGEPMap.
2335 auto GEPs = std::move(it->second);
2336 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2337 LargeOffsetGEPMap.erase(II);
2338 }
2339
2340 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2341 II->eraseFromParent();
2342 return true;
2343 }
2344 case Intrinsic::cttz:
2345 case Intrinsic::ctlz:
2346 // If counting zeros is expensive, try to avoid it.
2347 return despeculateCountZeros(II, TLI, DL, ModifiedDT, FreshBBs,
2348 IsHugeFunc);
2349 case Intrinsic::fshl:
2350 case Intrinsic::fshr:
2351 return optimizeFunnelShift(II);
2352 case Intrinsic::dbg_assign:
2353 case Intrinsic::dbg_value:
2354 return fixupDbgValue(II);
2355 case Intrinsic::masked_gather:
2356 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2357 case Intrinsic::masked_scatter:
2358 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2359 }
2360
2362 Type *AccessTy;
2363 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2364 while (!PtrOps.empty()) {
2365 Value *PtrVal = PtrOps.pop_back_val();
2366 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2367 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2368 return true;
2369 }
2370 }
2371
2372 // From here on out we're working with named functions.
2373 if (!CI->getCalledFunction())
2374 return false;
2375
2376 // Lower all default uses of _chk calls. This is very similar
2377 // to what InstCombineCalls does, but here we are only lowering calls
2378 // to fortified library functions (e.g. __memcpy_chk) that have the default
2379 // "don't know" as the objectsize. Anything else should be left alone.
2380 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2381 IRBuilder<> Builder(CI);
2382 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2383 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2384 CI->eraseFromParent();
2385 return true;
2386 }
2387
2388 return false;
2389}
2390
2391/// Look for opportunities to duplicate return instructions to the predecessor
2392/// to enable tail call optimizations. The case it is currently looking for is:
2393/// @code
2394/// bb0:
2395/// %tmp0 = tail call i32 @f0()
2396/// br label %return
2397/// bb1:
2398/// %tmp1 = tail call i32 @f1()
2399/// br label %return
2400/// bb2:
2401/// %tmp2 = tail call i32 @f2()
2402/// br label %return
2403/// return:
2404/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2405/// ret i32 %retval
2406/// @endcode
2407///
2408/// =>
2409///
2410/// @code
2411/// bb0:
2412/// %tmp0 = tail call i32 @f0()
2413/// ret i32 %tmp0
2414/// bb1:
2415/// %tmp1 = tail call i32 @f1()
2416/// ret i32 %tmp1
2417/// bb2:
2418/// %tmp2 = tail call i32 @f2()
2419/// ret i32 %tmp2
2420/// @endcode
2421bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2422 ModifyDT &ModifiedDT) {
2423 if (!BB->getTerminator())
2424 return false;
2425
2426 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2427 if (!RetI)
2428 return false;
2429
2430 PHINode *PN = nullptr;
2431 ExtractValueInst *EVI = nullptr;
2432 BitCastInst *BCI = nullptr;
2433 Value *V = RetI->getReturnValue();
2434 if (V) {
2435 BCI = dyn_cast<BitCastInst>(V);
2436 if (BCI)
2437 V = BCI->getOperand(0);
2438
2439 EVI = dyn_cast<ExtractValueInst>(V);
2440 if (EVI) {
2441 V = EVI->getOperand(0);
2442 if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; }))
2443 return false;
2444 }
2445
2446 PN = dyn_cast<PHINode>(V);
2447 if (!PN)
2448 return false;
2449 }
2450
2451 if (PN && PN->getParent() != BB)
2452 return false;
2453
2454 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
2455 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
2456 if (BC && BC->hasOneUse())
2457 Inst = BC->user_back();
2458
2459 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
2460 return II->getIntrinsicID() == Intrinsic::lifetime_end;
2461 return false;
2462 };
2463
2464 // Make sure there are no instructions between the first instruction
2465 // and return.
2466 const Instruction *BI = BB->getFirstNonPHI();
2467 // Skip over debug and the bitcast.
2468 while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI ||
2469 isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI))
2470 BI = BI->getNextNode();
2471 if (BI != RetI)
2472 return false;
2473
2474 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2475 /// call.
2476 const Function *F = BB->getParent();
2477 SmallVector<BasicBlock *, 4> TailCallBBs;
2478 if (PN) {
2479 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2480 // Look through bitcasts.
2481 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2482 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2483 BasicBlock *PredBB = PN->getIncomingBlock(I);
2484 // Make sure the phi value is indeed produced by the tail call.
2485 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2486 TLI->mayBeEmittedAsTailCall(CI) &&
2487 attributesPermitTailCall(F, CI, RetI, *TLI))
2488 TailCallBBs.push_back(PredBB);
2489 }
2490 } else {
2492 for (BasicBlock *Pred : predecessors(BB)) {
2493 if (!VisitedBBs.insert(Pred).second)
2494 continue;
2495 if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) {
2496 CallInst *CI = dyn_cast<CallInst>(I);
2497 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2498 attributesPermitTailCall(F, CI, RetI, *TLI))
2499 TailCallBBs.push_back(Pred);
2500 }
2501 }
2502 }
2503
2504 bool Changed = false;
2505 for (auto const &TailCallBB : TailCallBBs) {
2506 // Make sure the call instruction is followed by an unconditional branch to
2507 // the return block.
2508 BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
2509 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2510 continue;
2511
2512 // Duplicate the return into TailCallBB.
2513 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
2515 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
2516 BFI->setBlockFreq(
2517 BB,
2518 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency());
2519 ModifiedDT = ModifyDT::ModifyBBDT;
2520 Changed = true;
2521 ++NumRetsDup;
2522 }
2523
2524 // If we eliminated all predecessors of the block, delete the block now.
2525 if (Changed && !BB->hasAddressTaken() && pred_empty(BB))
2526 BB->eraseFromParent();
2527
2528 return Changed;
2529}
2530
2531//===----------------------------------------------------------------------===//
2532// Memory Optimization
2533//===----------------------------------------------------------------------===//
2534
2535namespace {
2536
2537/// This is an extended version of TargetLowering::AddrMode
2538/// which holds actual Value*'s for register values.
2539struct ExtAddrMode : public TargetLowering::AddrMode {
2540 Value *BaseReg = nullptr;
2541 Value *ScaledReg = nullptr;
2542 Value *OriginalValue = nullptr;
2543 bool InBounds = true;
2544
2545 enum FieldName {
2546 NoField = 0x00,
2547 BaseRegField = 0x01,
2548 BaseGVField = 0x02,
2549 BaseOffsField = 0x04,
2550 ScaledRegField = 0x08,
2551 ScaleField = 0x10,
2552 MultipleFields = 0xff
2553 };
2554
2555 ExtAddrMode() = default;
2556
2557 void print(raw_ostream &OS) const;
2558 void dump() const;
2559
2560 FieldName compare(const ExtAddrMode &other) {
2561 // First check that the types are the same on each field, as differing types
2562 // is something we can't cope with later on.
2563 if (BaseReg && other.BaseReg &&
2564 BaseReg->getType() != other.BaseReg->getType())
2565 return MultipleFields;
2566 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
2567 return MultipleFields;
2568 if (ScaledReg && other.ScaledReg &&
2569 ScaledReg->getType() != other.ScaledReg->getType())
2570 return MultipleFields;
2571
2572 // Conservatively reject 'inbounds' mismatches.
2573 if (InBounds != other.InBounds)
2574 return MultipleFields;
2575
2576 // Check each field to see if it differs.
2577 unsigned Result = NoField;
2578 if (BaseReg != other.BaseReg)
2579 Result |= BaseRegField;
2580 if (BaseGV != other.BaseGV)
2581 Result |= BaseGVField;
2582 if (BaseOffs != other.BaseOffs)
2583 Result |= BaseOffsField;
2584 if (ScaledReg != other.ScaledReg)
2585 Result |= ScaledRegField;
2586 // Don't count 0 as being a different scale, because that actually means
2587 // unscaled (which will already be counted by having no ScaledReg).
2588 if (Scale && other.Scale && Scale != other.Scale)
2589 Result |= ScaleField;
2590
2591 if (llvm::popcount(Result) > 1)
2592 return MultipleFields;
2593 else
2594 return static_cast<FieldName>(Result);
2595 }
2596
2597 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2598 // with no offset.
2599 bool isTrivial() {
2600 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2601 // trivial if at most one of these terms is nonzero, except that BaseGV and
2602 // BaseReg both being zero actually means a null pointer value, which we
2603 // consider to be 'non-zero' here.
2604 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
2605 }
2606
2607 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2608 switch (Field) {
2609 default:
2610 return nullptr;
2611 case BaseRegField:
2612 return BaseReg;
2613 case BaseGVField:
2614 return BaseGV;
2615 case ScaledRegField:
2616 return ScaledReg;
2617 case BaseOffsField:
2618 return ConstantInt::get(IntPtrTy, BaseOffs);
2619 }
2620 }
2621
2622 void SetCombinedField(FieldName Field, Value *V,
2623 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2624 switch (Field) {
2625 default:
2626 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2627 break;
2628 case ExtAddrMode::BaseRegField:
2629 BaseReg = V;
2630 break;
2631 case ExtAddrMode::BaseGVField:
2632 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2633 // in the BaseReg field.
2634 assert(BaseReg == nullptr);
2635 BaseReg = V;
2636 BaseGV = nullptr;
2637 break;
2638 case ExtAddrMode::ScaledRegField:
2639 ScaledReg = V;
2640 // If we have a mix of scaled and unscaled addrmodes then we want scale
2641 // to be the scale and not zero.
2642 if (!Scale)
2643 for (const ExtAddrMode &AM : AddrModes)
2644 if (AM.Scale) {
2645 Scale = AM.Scale;
2646 break;
2647 }
2648 break;
2649 case ExtAddrMode::BaseOffsField:
2650 // The offset is no longer a constant, so it goes in ScaledReg with a
2651 // scale of 1.
2652 assert(ScaledReg == nullptr);
2653 ScaledReg = V;
2654 Scale = 1;
2655 BaseOffs = 0;
2656 break;
2657 }
2658 }
2659};
2660
2661#ifndef NDEBUG
2662static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2663 AM.print(OS);
2664 return OS;
2665}
2666#endif
2667
2668#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2669void ExtAddrMode::print(raw_ostream &OS) const {
2670 bool NeedPlus = false;
2671 OS << "[";
2672 if (InBounds)
2673 OS << "inbounds ";
2674 if (BaseGV) {
2675 OS << "GV:";
2676 BaseGV->printAsOperand(OS, /*PrintType=*/false);
2677 NeedPlus = true;
2678 }
2679
2680 if (BaseOffs) {
2681 OS << (NeedPlus ? " + " : "") << BaseOffs;
2682 NeedPlus = true;
2683 }
2684
2685 if (BaseReg) {
2686 OS << (NeedPlus ? " + " : "") << "Base:";
2687 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2688 NeedPlus = true;
2689 }
2690 if (Scale) {
2691 OS << (NeedPlus ? " + " : "") << Scale << "*";
2692 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2693 }
2694
2695 OS << ']';
2696}
2697
2698LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
2699 print(dbgs());
2700 dbgs() << '\n';
2701}
2702#endif
2703
2704} // end anonymous namespace
2705
2706namespace {
2707
2708/// This class provides transaction based operation on the IR.
2709/// Every change made through this class is recorded in the internal state and
2710/// can be undone (rollback) until commit is called.
2711/// CGP does not check if instructions could be speculatively executed when
2712/// moved. Preserving the original location would pessimize the debugging
2713/// experience, as well as negatively impact the quality of sample PGO.
2714class TypePromotionTransaction {
2715 /// This represents the common interface of the individual transaction.
2716 /// Each class implements the logic for doing one specific modification on
2717 /// the IR via the TypePromotionTransaction.
2718 class TypePromotionAction {
2719 protected:
2720 /// The Instruction modified.
2721 Instruction *Inst;
2722
2723 public:
2724 /// Constructor of the action.
2725 /// The constructor performs the related action on the IR.
2726 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2727
2728 virtual ~TypePromotionAction() = default;
2729
2730 /// Undo the modification done by this action.
2731 /// When this method is called, the IR must be in the same state as it was
2732 /// before this action was applied.
2733 /// \pre Undoing the action works if and only if the IR is in the exact same
2734 /// state as it was directly after this action was applied.
2735 virtual void undo() = 0;
2736
2737 /// Advocate every change made by this action.
2738 /// When the results on the IR of the action are to be kept, it is important
2739 /// to call this function, otherwise hidden information may be kept forever.
2740 virtual void commit() {
2741 // Nothing to be done, this action is not doing anything.
2742 }
2743 };
2744
2745 /// Utility to remember the position of an instruction.
2746 class InsertionHandler {
2747 /// Position of an instruction.
2748 /// Either an instruction:
2749 /// - Is the first in a basic block: BB is used.
2750 /// - Has a previous instruction: PrevInst is used.
2751 union {
2752 Instruction *PrevInst;
2753 BasicBlock *BB;
2754 } Point;
2755
2756 /// Remember whether or not the instruction had a previous instruction.
2757 bool HasPrevInstruction;
2758
2759 public:
2760 /// Record the position of \p Inst.
2761 InsertionHandler(Instruction *Inst) {
2762 BasicBlock::iterator It = Inst->getIterator();
2763 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2764 if (HasPrevInstruction)
2765 Point.PrevInst = &*--It;
2766 else
2767 Point.BB = Inst->getParent();
2768 }
2769
2770 /// Insert \p Inst at the recorded position.
2771 void insert(Instruction *Inst) {
2772 if (HasPrevInstruction) {
2773 if (Inst->getParent())
2774 Inst->removeFromParent();
2775 Inst->insertAfter(Point.PrevInst);
2776 } else {
2777 Instruction *Position = &*Point.BB->getFirstInsertionPt();
2778 if (Inst->getParent())
2779 Inst->moveBefore(Position);
2780 else
2781 Inst->insertBefore(Position);
2782 }
2783 }
2784 };
2785
2786 /// Move an instruction before another.
2787 class InstructionMoveBefore : public TypePromotionAction {
2788 /// Original position of the instruction.
2789 InsertionHandler Position;
2790
2791 public:
2792 /// Move \p Inst before \p Before.
2793 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2794 : TypePromotionAction(Inst), Position(Inst) {
2795 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2796 << "\n");
2797 Inst->moveBefore(Before);
2798 }
2799
2800 /// Move the instruction back to its original position.
2801 void undo() override {
2802 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2803 Position.insert(Inst);
2804 }
2805 };
2806
2807 /// Set the operand of an instruction with a new value.
2808 class OperandSetter : public TypePromotionAction {
2809 /// Original operand of the instruction.
2810 Value *Origin;
2811
2812 /// Index of the modified instruction.
2813 unsigned Idx;
2814
2815 public:
2816 /// Set \p Idx operand of \p Inst with \p NewVal.
2817 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2818 : TypePromotionAction(Inst), Idx(Idx) {
2819 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2820 << "for:" << *Inst << "\n"
2821 << "with:" << *NewVal << "\n");
2822 Origin = Inst->getOperand(Idx);
2823 Inst->setOperand(Idx, NewVal);
2824 }
2825
2826 /// Restore the original value of the instruction.
2827 void undo() override {
2828 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2829 << "for: " << *Inst << "\n"
2830 << "with: " << *Origin << "\n");
2831 Inst->setOperand(Idx, Origin);
2832 }
2833 };
2834
2835 /// Hide the operands of an instruction.
2836 /// Do as if this instruction was not using any of its operands.
2837 class OperandsHider : public TypePromotionAction {
2838 /// The list of original operands.
2839 SmallVector<Value *, 4> OriginalValues;
2840
2841 public:
2842 /// Remove \p Inst from the uses of the operands of \p Inst.
2843 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2844 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2845 unsigned NumOpnds = Inst->getNumOperands();
2846 OriginalValues.reserve(NumOpnds);
2847 for (unsigned It = 0; It < NumOpnds; ++It) {
2848 // Save the current operand.
2849 Value *Val = Inst->getOperand(It);
2850 OriginalValues.push_back(Val);
2851 // Set a dummy one.
2852 // We could use OperandSetter here, but that would imply an overhead
2853 // that we are not willing to pay.
2854 Inst->setOperand(It, UndefValue::get(Val->getType()));
2855 }
2856 }
2857
2858 /// Restore the original list of uses.
2859 void undo() override {
2860 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2861 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2862 Inst->setOperand(It, OriginalValues[It]);
2863 }
2864 };
2865
2866 /// Build a truncate instruction.
2867 class TruncBuilder : public TypePromotionAction {
2868 Value *Val;
2869
2870 public:
2871 /// Build a truncate instruction of \p Opnd producing a \p Ty
2872 /// result.
2873 /// trunc Opnd to Ty.
2874 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2875 IRBuilder<> Builder(Opnd);
2876 Builder.SetCurrentDebugLocation(DebugLoc());
2877 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2878 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
2879 }
2880
2881 /// Get the built value.
2882 Value *getBuiltValue() { return Val; }
2883
2884 /// Remove the built instruction.
2885 void undo() override {
2886 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2887 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2888 IVal->eraseFromParent();
2889 }
2890 };
2891
2892 /// Build a sign extension instruction.
2893 class SExtBuilder : public TypePromotionAction {
2894 Value *Val;
2895
2896 public:
2897 /// Build a sign extension instruction of \p Opnd producing a \p Ty
2898 /// result.
2899 /// sext Opnd to Ty.
2900 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2901 : TypePromotionAction(InsertPt) {
2902 IRBuilder<> Builder(InsertPt);
2903 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2904 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
2905 }
2906
2907 /// Get the built value.
2908 Value *getBuiltValue() { return Val; }
2909
2910 /// Remove the built instruction.
2911 void undo() override {
2912 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2913 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2914 IVal->eraseFromParent();
2915 }
2916 };
2917
2918 /// Build a zero extension instruction.
2919 class ZExtBuilder : public TypePromotionAction {
2920 Value *Val;
2921
2922 public:
2923 /// Build a zero extension instruction of \p Opnd producing a \p Ty
2924 /// result.
2925 /// zext Opnd to Ty.
2926 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2927 : TypePromotionAction(InsertPt) {
2928 IRBuilder<> Builder(InsertPt);
2929 Builder.SetCurrentDebugLocation(DebugLoc());
2930 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2931 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
2932 }
2933
2934 /// Get the built value.
2935 Value *getBuiltValue() { return Val; }
2936
2937 /// Remove the built instruction.
2938 void undo() override {
2939 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2940 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2941 IVal->eraseFromParent();
2942 }
2943 };
2944
2945 /// Mutate an instruction to another type.
2946 class TypeMutator : public TypePromotionAction {
2947 /// Record the original type.
2948 Type *OrigTy;
2949
2950 public:
2951 /// Mutate the type of \p Inst into \p NewTy.
2952 TypeMutator(Instruction *Inst, Type *NewTy)
2953 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2954 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2955 << "\n");
2956 Inst->mutateType(NewTy);
2957 }
2958
2959 /// Mutate the instruction back to its original type.
2960 void undo() override {
2961 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2962 << "\n");
2963 Inst->mutateType(OrigTy);
2964 }
2965 };
2966
2967 /// Replace the uses of an instruction by another instruction.
2968 class UsesReplacer : public TypePromotionAction {
2969 /// Helper structure to keep track of the replaced uses.
2970 struct InstructionAndIdx {
2971 /// The instruction using the instruction.
2972 Instruction *Inst;
2973
2974 /// The index where this instruction is used for Inst.
2975 unsigned Idx;
2976
2977 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2978 : Inst(Inst), Idx(Idx) {}
2979 };
2980
2981 /// Keep track of the original uses (pair Instruction, Index).
2983 /// Keep track of the debug users.
2985
2986 /// Keep track of the new value so that we can undo it by replacing
2987 /// instances of the new value with the original value.
2988 Value *New;
2989
2991
2992 public:
2993 /// Replace all the use of \p Inst by \p New.
2994 UsesReplacer(Instruction *Inst, Value *New)
2995 : TypePromotionAction(Inst), New(New) {
2996 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2997 << "\n");
2998 // Record the original uses.
2999 for (Use &U : Inst->uses()) {
3000 Instruction *UserI = cast<Instruction>(U.getUser());
3001 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3002 }
3003 // Record the debug uses separately. They are not in the instruction's
3004 // use list, but they are replaced by RAUW.
3005 findDbgValues(DbgValues, Inst);
3006
3007 // Now, we can replace the uses.
3008 Inst->replaceAllUsesWith(New);
3009 }
3010
3011 /// Reassign the original uses of Inst to Inst.
3012 void undo() override {
3013 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3014 for (InstructionAndIdx &Use : OriginalUses)
3015 Use.Inst->setOperand(Use.Idx, Inst);
3016 // RAUW has replaced all original uses with references to the new value,
3017 // including the debug uses. Since we are undoing the replacements,
3018 // the original debug uses must also be reinstated to maintain the
3019 // correctness and utility of debug value instructions.
3020 for (auto *DVI : DbgValues)
3021 DVI->replaceVariableLocationOp(New, Inst);
3022 }
3023 };
3024
3025 /// Remove an instruction from the IR.
3026 class InstructionRemover : public TypePromotionAction {
3027 /// Original position of the instruction.
3028 InsertionHandler Inserter;
3029
3030 /// Helper structure to hide all the link to the instruction. In other
3031 /// words, this helps to do as if the instruction was removed.
3032 OperandsHider Hider;
3033
3034 /// Keep track of the uses replaced, if any.
3035 UsesReplacer *Replacer = nullptr;
3036
3037 /// Keep track of instructions removed.
3038 SetOfInstrs &RemovedInsts;
3039
3040 public:
3041 /// Remove all reference of \p Inst and optionally replace all its
3042 /// uses with New.
3043 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3044 /// \pre If !Inst->use_empty(), then New != nullptr
3045 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3046 Value *New = nullptr)
3047 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3048 RemovedInsts(RemovedInsts) {
3049 if (New)
3050 Replacer = new UsesReplacer(Inst, New);
3051 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3052 RemovedInsts.insert(Inst);
3053 /// The instructions removed here will be freed after completing
3054 /// optimizeBlock() for all blocks as we need to keep track of the
3055 /// removed instructions during promotion.
3056 Inst->removeFromParent();
3057 }
3058
3059 ~InstructionRemover() override { delete Replacer; }
3060
3061 /// Resurrect the instruction and reassign it to the proper uses if
3062 /// new value was provided when build this action.
3063 void undo() override {
3064 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3065 Inserter.insert(Inst);
3066 if (Replacer)
3067 Replacer->undo();
3068 Hider.undo();
3069 RemovedInsts.erase(Inst);
3070 }
3071 };
3072
3073public:
3074 /// Restoration point.
3075 /// The restoration point is a pointer to an action instead of an iterator
3076 /// because the iterator may be invalidated but not the pointer.
3077 using ConstRestorationPt = const TypePromotionAction *;
3078
3079 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3080 : RemovedInsts(RemovedInsts) {}
3081
3082 /// Advocate every changes made in that transaction. Return true if any change
3083 /// happen.
3084 bool commit();
3085
3086 /// Undo all the changes made after the given point.
3087 void rollback(ConstRestorationPt Point);
3088
3089 /// Get the current restoration point.
3090 ConstRestorationPt getRestorationPoint() const;
3091
3092 /// \name API for IR modification with state keeping to support rollback.
3093 /// @{
3094 /// Same as Instruction::setOperand.
3095 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3096
3097 /// Same as Instruction::eraseFromParent.
3098 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3099
3100 /// Same as Value::replaceAllUsesWith.
3101 void replaceAllUsesWith(Instruction *Inst, Value *New);
3102
3103 /// Same as Value::mutateType.
3104 void mutateType(Instruction *Inst, Type *NewTy);
3105
3106 /// Same as IRBuilder::createTrunc.
3107 Value *createTrunc(Instruction *Opnd, Type *Ty);
3108
3109 /// Same as IRBuilder::createSExt.
3110 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3111
3112 /// Same as IRBuilder::createZExt.
3113 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3114
3115 /// Same as Instruction::moveBefore.
3116 void moveBefore(Instruction *Inst, Instruction *Before);
3117 /// @}
3118
3119private:
3120 /// The ordered list of actions made so far.
3122
3123 using CommitPt =
3125
3126 SetOfInstrs &RemovedInsts;
3127};
3128
3129} // end anonymous namespace
3130
3131void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3132 Value *NewVal) {
3133 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3134 Inst, Idx, NewVal));
3135}
3136
3137void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3138 Value *NewVal) {
3139 Actions.push_back(
3140 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3141 Inst, RemovedInsts, NewVal));
3142}
3143
3144void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3145 Value *New) {
3146 Actions.push_back(
3147 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3148}
3149
3150void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3151 Actions.push_back(
3152 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3153}
3154
3155Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3156 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3157 Value *Val = Ptr->getBuiltValue();
3158 Actions.push_back(std::move(Ptr));
3159 return Val;
3160}
3161
3162Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3163 Type *Ty) {
3164 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3165 Value *Val = Ptr->getBuiltValue();
3166 Actions.push_back(std::move(Ptr));
3167 return Val;
3168}
3169
3170Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3171 Type *Ty) {
3172 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3173 Value *Val = Ptr->getBuiltValue();
3174 Actions.push_back(std::move(Ptr));
3175 return Val;
3176}
3177
3178void TypePromotionTransaction::moveBefore(Instruction *Inst,
3179 Instruction *Before) {
3180 Actions.push_back(
3181 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
3182 Inst, Before));
3183}
3184
3185TypePromotionTransaction::ConstRestorationPt
3186TypePromotionTransaction::getRestorationPoint() const {
3187 return !Actions.empty() ? Actions.back().get() : nullptr;
3188}
3189
3190bool TypePromotionTransaction::commit() {
3191 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3192 Action->commit();
3193 bool Modified = !Actions.empty();
3194 Actions.clear();
3195 return Modified;
3196}
3197
3198void TypePromotionTransaction::rollback(
3199 TypePromotionTransaction::ConstRestorationPt Point) {
3200 while (!Actions.empty() && Point != Actions.back().get()) {
3201 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3202 Curr->undo();
3203 }
3204}
3205
3206namespace {
3207
3208/// A helper class for matching addressing modes.
3209///
3210/// This encapsulates the logic for matching the target-legal addressing modes.
3211class AddressingModeMatcher {
3212 SmallVectorImpl<Instruction *> &AddrModeInsts;
3213 const TargetLowering &TLI;
3214 const TargetRegisterInfo &TRI;
3215 const DataLayout &DL;
3216 const LoopInfo &LI;
3217 const std::function<const DominatorTree &()> getDTFn;
3218
3219 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3220 /// the memory instruction that we're computing this address for.
3221 Type *AccessTy;
3222 unsigned AddrSpace;
3223 Instruction *MemoryInst;
3224
3225 /// This is the addressing mode that we're building up. This is
3226 /// part of the return value of this addressing mode matching stuff.
3228
3229 /// The instructions inserted by other CodeGenPrepare optimizations.
3230 const SetOfInstrs &InsertedInsts;
3231
3232 /// A map from the instructions to their type before promotion.
3233 InstrToOrigTy &PromotedInsts;
3234
3235 /// The ongoing transaction where every action should be registered.
3236 TypePromotionTransaction &TPT;
3237
3238 // A GEP which has too large offset to be folded into the addressing mode.
3239 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3240
3241 /// This is set to true when we should not do profitability checks.
3242 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3243 bool IgnoreProfitability;
3244
3245 /// True if we are optimizing for size.
3246 bool OptSize;
3247
3248 ProfileSummaryInfo *PSI;
3250
3251 AddressingModeMatcher(
3253 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3254 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3255 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3256 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3257 TypePromotionTransaction &TPT,
3258 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3259 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3260 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3261 DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn),
3262 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3263 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3264 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3265 IgnoreProfitability = false;
3266 }
3267
3268public:
3269 /// Find the maximal addressing mode that a load/store of V can fold,
3270 /// give an access type of AccessTy. This returns a list of involved
3271 /// instructions in AddrModeInsts.
3272 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3273 /// optimizations.
3274 /// \p PromotedInsts maps the instructions to their type before promotion.
3275 /// \p The ongoing transaction where every action should be registered.
3276 static ExtAddrMode
3277 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3278 SmallVectorImpl<Instruction *> &AddrModeInsts,
3279 const TargetLowering &TLI, const LoopInfo &LI,
3280 const std::function<const DominatorTree &()> getDTFn,
3281 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3282 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3283 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3284 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3286
3287 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
3288 AccessTy, AS, MemoryInst, Result,
3289 InsertedInsts, PromotedInsts, TPT,
3290 LargeOffsetGEP, OptSize, PSI, BFI)
3291 .matchAddr(V, 0);
3292 (void)Success;
3293 assert(Success && "Couldn't select *anything*?");
3294 return Result;
3295 }
3296
3297private:
3298 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3299 bool matchAddr(Value *Addr, unsigned Depth);
3300 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3301 bool *MovedAway = nullptr);
3302 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3303 ExtAddrMode &AMBefore,
3304 ExtAddrMode &AMAfter);
3305 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3306 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3307 Value *PromotedOperand) const;
3308};
3309
3310class PhiNodeSet;
3311
3312/// An iterator for PhiNodeSet.
3313class PhiNodeSetIterator {
3314 PhiNodeSet *const Set;
3315 size_t CurrentIndex = 0;
3316
3317public:
3318 /// The constructor. Start should point to either a valid element, or be equal
3319 /// to the size of the underlying SmallVector of the PhiNodeSet.
3320 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3321 PHINode *operator*() const;
3322 PhiNodeSetIterator &operator++();
3323 bool operator==(const PhiNodeSetIterator &RHS) const;
3324 bool operator!=(const PhiNodeSetIterator &RHS) const;
3325};
3326
3327/// Keeps a set of PHINodes.
3328///
3329/// This is a minimal set implementation for a specific use case:
3330/// It is very fast when there are very few elements, but also provides good
3331/// performance when there are many. It is similar to SmallPtrSet, but also
3332/// provides iteration by insertion order, which is deterministic and stable
3333/// across runs. It is also similar to SmallSetVector, but provides removing
3334/// elements in O(1) time. This is achieved by not actually removing the element
3335/// from the underlying vector, so comes at the cost of using more memory, but
3336/// that is fine, since PhiNodeSets are used as short lived objects.
3337class PhiNodeSet {
3338 friend class PhiNodeSetIterator;
3339
3341 using iterator = PhiNodeSetIterator;
3342
3343 /// Keeps the elements in the order of their insertion in the underlying
3344 /// vector. To achieve constant time removal, it never deletes any element.
3346
3347 /// Keeps the elements in the underlying set implementation. This (and not the
3348 /// NodeList defined above) is the source of truth on whether an element
3349 /// is actually in the collection.
3350 MapType NodeMap;
3351
3352 /// Points to the first valid (not deleted) element when the set is not empty
3353 /// and the value is not zero. Equals to the size of the underlying vector
3354 /// when the set is empty. When the value is 0, as in the beginning, the
3355 /// first element may or may not be valid.
3356 size_t FirstValidElement = 0;
3357
3358public:
3359 /// Inserts a new element to the collection.
3360 /// \returns true if the element is actually added, i.e. was not in the
3361 /// collection before the operation.
3362 bool insert(PHINode *Ptr) {
3363 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3364 NodeList.push_back(Ptr);
3365 return true;
3366 }
3367 return false;
3368 }
3369
3370 /// Removes the element from the collection.
3371 /// \returns whether the element is actually removed, i.e. was in the
3372 /// collection before the operation.
3373 bool erase(PHINode *Ptr) {
3374 if (NodeMap.erase(Ptr)) {
3375 SkipRemovedElements(FirstValidElement);
3376 return true;
3377 }
3378 return false;
3379 }
3380
3381 /// Removes all elements and clears the collection.
3382 void clear() {
3383 NodeMap.clear();
3384 NodeList.clear();
3385 FirstValidElement = 0;
3386 }
3387
3388 /// \returns an iterator that will iterate the elements in the order of
3389 /// insertion.
3390 iterator begin() {
3391 if (FirstValidElement == 0)
3392 SkipRemovedElements(FirstValidElement);
3393 return PhiNodeSetIterator(this, FirstValidElement);
3394 }
3395
3396 /// \returns an iterator that points to the end of the collection.
3397 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3398
3399 /// Returns the number of elements in the collection.
3400 size_t size() const { return NodeMap.size(); }
3401
3402 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3403 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
3404
3405private:
3406 /// Updates the CurrentIndex so that it will point to a valid element.
3407 ///
3408 /// If the element of NodeList at CurrentIndex is valid, it does not
3409 /// change it. If there are no more valid elements, it updates CurrentIndex
3410 /// to point to the end of the NodeList.
3411 void SkipRemovedElements(size_t &CurrentIndex) {
3412 while (CurrentIndex < NodeList.size()) {
3413 auto it = NodeMap.find(NodeList[CurrentIndex]);
3414 // If the element has been deleted and added again later, NodeMap will
3415 // point to a different index, so CurrentIndex will still be invalid.
3416 if (it != NodeMap.end() && it->second == CurrentIndex)
3417 break;
3418 ++CurrentIndex;
3419 }
3420 }
3421};
3422
3423PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3424 : Set(Set), CurrentIndex(Start) {}
3425
3426PHINode *PhiNodeSetIterator::operator*() const {
3427 assert(CurrentIndex < Set->NodeList.size() &&
3428 "PhiNodeSet access out of range");
3429 return Set->NodeList[CurrentIndex];
3430}
3431
3432PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
3433 assert(CurrentIndex < Set->NodeList.size() &&
3434 "PhiNodeSet access out of range");
3435 ++CurrentIndex;
3436 Set->SkipRemovedElements(CurrentIndex);
3437 return *this;
3438}
3439
3440bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3441 return CurrentIndex == RHS.CurrentIndex;
3442}
3443
3444bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3445 return !((*this) == RHS);
3446}
3447
3448/// Keep track of simplification of Phi nodes.
3449/// Accept the set of all phi nodes and erase phi node from this set
3450/// if it is simplified.
3451class SimplificationTracker {
3453 const SimplifyQuery &SQ;
3454 // Tracks newly created Phi nodes. The elements are iterated by insertion
3455 // order.
3456 PhiNodeSet AllPhiNodes;
3457 // Tracks newly created Select nodes.
3458 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3459
3460public:
3461 SimplificationTracker(const SimplifyQuery &sq) : SQ(sq) {}
3462
3463 Value *Get(Value *V) {
3464 do {
3465 auto SV = Storage.find(V);
3466 if (SV == Storage.end())
3467 return V;
3468 V = SV->second;
3469 } while (true);
3470 }
3471
3472 Value *Simplify(Value *Val) {
3473 SmallVector<Value *, 32> WorkList;
3475 WorkList.push_back(Val);
3476 while (!WorkList.empty()) {
3477 auto *P = WorkList.pop_back_val();
3478 if (!Visited.insert(P).second)
3479 continue;
3480 if (auto *PI = dyn_cast<Instruction>(P))
3481 if (Value *V = simplifyInstruction(cast<Instruction>(PI), SQ)) {
3482 for (auto *U : PI->users())
3483 WorkList.push_back(cast<Value>(U));
3484 Put(PI, V);
3485 PI->replaceAllUsesWith(V);
3486 if (auto *PHI = dyn_cast<PHINode>(PI))
3487 AllPhiNodes.erase(PHI);
3488 if (auto *Select = dyn_cast<SelectInst>(PI))
3489 AllSelectNodes.erase(Select);
3490 PI->eraseFromParent();
3491 }
3492 }
3493 return Get(Val);
3494 }
3495
3496 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
3497
3498 void ReplacePhi(PHINode *From, PHINode *To) {
3499 Value *OldReplacement = Get(From);
3500 while (OldReplacement != From) {
3501 From = To;
3502 To = dyn_cast<PHINode>(OldReplacement);
3503 OldReplacement = Get(From);
3504 }
3505 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
3506 Put(From, To);
3507 From->replaceAllUsesWith(To);
3508 AllPhiNodes.erase(From);
3509 From->eraseFromParent();
3510 }
3511
3512 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
3513
3514 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3515
3516 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3517
3518 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3519
3520 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3521
3522 void destroyNewNodes(Type *CommonType) {
3523 // For safe erasing, replace the uses with dummy value first.
3524 auto *Dummy = PoisonValue::get(CommonType);
3525 for (auto *I : AllPhiNodes) {
3526 I->replaceAllUsesWith(Dummy);
3527 I->eraseFromParent();
3528 }
3529 AllPhiNodes.clear();
3530 for (auto *I : AllSelectNodes) {
3531 I->replaceAllUsesWith(Dummy);
3532 I->eraseFromParent();
3533 }
3534 AllSelectNodes.clear();
3535 }
3536};
3537
3538/// A helper class for combining addressing modes.
3539class AddressingModeCombiner {
3540 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3541 typedef std::pair<PHINode *, PHINode *> PHIPair;
3542
3543private:
3544 /// The addressing modes we've collected.
3546
3547 /// The field in which the AddrModes differ, when we have more than one.
3548 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3549
3550 /// Are the AddrModes that we have all just equal to their original values?
3551 bool AllAddrModesTrivial = true;
3552
3553 /// Common Type for all different fields in addressing modes.
3554 Type *CommonType = nullptr;
3555
3556 /// SimplifyQuery for simplifyInstruction utility.
3557 const SimplifyQuery &SQ;
3558
3559 /// Original Address.
3560 Value *Original;
3561
3562public:
3563 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
3564 : SQ(_SQ), Original(OriginalValue) {}
3565
3566 /// Get the combined AddrMode
3567 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
3568
3569 /// Add a new AddrMode if it's compatible with the AddrModes we already
3570 /// have.
3571 /// \return True iff we succeeded in doing so.
3572 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3573 // Take note of if we have any non-trivial AddrModes, as we need to detect
3574 // when all AddrModes are trivial as then we would introduce a phi or select
3575 // which just duplicates what's already there.
3576 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3577
3578 // If this is the first addrmode then everything is fine.
3579 if (AddrModes.empty()) {
3580 AddrModes.emplace_back(NewAddrMode);
3581 return true;
3582 }
3583
3584 // Figure out how different this is from the other address modes, which we
3585 // can do just by comparing against the first one given that we only care
3586 // about the cumulative difference.
3587 ExtAddrMode::FieldName ThisDifferentField =
3588 AddrModes[0].compare(NewAddrMode);
3589 if (DifferentField == ExtAddrMode::NoField)
3590 DifferentField = ThisDifferentField;
3591 else if (DifferentField != ThisDifferentField)
3592 DifferentField = ExtAddrMode::MultipleFields;
3593
3594 // If NewAddrMode differs in more than one dimension we cannot handle it.
3595 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3596
3597 // If Scale Field is different then we reject.
3598 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3599
3600 // We also must reject the case when base offset is different and
3601 // scale reg is not null, we cannot handle this case due to merge of
3602 // different offsets will be used as ScaleReg.
3603 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3604 !NewAddrMode.ScaledReg);
3605
3606 // We also must reject the case when GV is different and BaseReg installed
3607 // due to we want to use base reg as a merge of GV values.
3608 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3609 !NewAddrMode.HasBaseReg);
3610
3611 // Even if NewAddMode is the same we still need to collect it due to
3612 // original value is different. And later we will need all original values
3613 // as anchors during finding the common Phi node.
3614 if (CanHandle)
3615 AddrModes.emplace_back(NewAddrMode);
3616 else
3617 AddrModes.clear();
3618
3619 return CanHandle;
3620 }
3621
3622 /// Combine the addressing modes we've collected into a single
3623 /// addressing mode.
3624 /// \return True iff we successfully combined them or we only had one so
3625 /// didn't need to combine them anyway.
3626 bool combineAddrModes() {
3627 // If we have no AddrModes then they can't be combined.
3628 if (AddrModes.size() == 0)
3629 return false;
3630
3631 // A single AddrMode can trivially be combined.
3632 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
3633 return true;
3634
3635 // If the AddrModes we collected are all just equal to the value they are
3636 // derived from then combining them wouldn't do anything useful.
3637 if (AllAddrModesTrivial)
3638 return false;
3639
3640 if (!addrModeCombiningAllowed())
3641 return false;
3642
3643 // Build a map between <original value, basic block where we saw it> to
3644 // value of base register.
3645 // Bail out if there is no common type.
3646 FoldAddrToValueMapping Map;
3647 if (!initializeMap(Map))
3648 return false;
3649
3650 Value *CommonValue = findCommon(Map);
3651 if (CommonValue)
3652 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
3653 return CommonValue != nullptr;
3654 }
3655
3656private:
3657 /// Initialize Map with anchor values. For address seen
3658 /// we set the value of different field saw in this address.
3659 /// At the same time we find a common type for different field we will
3660 /// use to create new Phi/Select nodes. Keep it in CommonType field.
3661 /// Return false if there is no common type found.
3662 bool initializeMap(FoldAddrToValueMapping &Map) {
3663 // Keep track of keys where the value is null. We will need to replace it
3664 // with constant null when we know the common type.
3665 SmallVector<Value *, 2> NullValue;
3666 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
3667 for (auto &AM : AddrModes) {
3668 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
3669 if (DV) {
3670 auto *Type = DV->getType();
3671 if (CommonType && CommonType != Type)
3672 return false;
3673 CommonType = Type;
3674 Map[AM.OriginalValue] = DV;
3675 } else {
3676 NullValue.push_back(AM.OriginalValue);
3677 }
3678 }
3679 assert(CommonType && "At least one non-null value must be!");
3680 for (auto *V : NullValue)
3681 Map[V] = Constant::getNullValue(CommonType);
3682 return true;
3683 }
3684
3685 /// We have mapping between value A and other value B where B was a field in
3686 /// addressing mode represented by A. Also we have an original value C
3687 /// representing an address we start with. Traversing from C through phi and
3688 /// selects we ended up with A's in a map. This utility function tries to find
3689 /// a value V which is a field in addressing mode C and traversing through phi
3690 /// nodes and selects we will end up in corresponded values B in a map.
3691 /// The utility will create a new Phi/Selects if needed.
3692 // The simple example looks as follows:
3693 // BB1:
3694 // p1 = b1 + 40
3695 // br cond BB2, BB3
3696 // BB2:
3697 // p2 = b2 + 40
3698 // br BB3
3699 // BB3:
3700 // p = phi [p1, BB1], [p2, BB2]
3701 // v = load p
3702 // Map is
3703 // p1 -> b1
3704 // p2 -> b2
3705 // Request is
3706 // p -> ?
3707 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
3708 Value *findCommon(FoldAddrToValueMapping &Map) {
3709 // Tracks the simplification of newly created phi nodes. The reason we use
3710 // this mapping is because we will add new created Phi nodes in AddrToBase.
3711 // Simplification of Phi nodes is recursive, so some Phi node may
3712 // be simplified after we added it to AddrToBase. In reality this
3713 // simplification is possible only if original phi/selects were not
3714 // simplified yet.
3715 // Using this mapping we can find the current value in AddrToBase.
3716 SimplificationTracker ST(SQ);
3717
3718 // First step, DFS to create PHI nodes for all intermediate blocks.
3719 // Also fill traverse order for the second step.
3720 SmallVector<Value *, 32> TraverseOrder;
3721 InsertPlaceholders(Map, TraverseOrder, ST);
3722
3723 // Second Step, fill new nodes by merged values and simplify if possible.
3724 FillPlaceholders(Map, TraverseOrder, ST);
3725
3726 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3727 ST.destroyNewNodes(CommonType);
3728 return nullptr;
3729 }
3730
3731 // Now we'd like to match New Phi nodes to existed ones.
3732 unsigned PhiNotMatchedCount = 0;
3733 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3734 ST.destroyNewNodes(CommonType);
3735 return nullptr;
3736 }
3737
3738 auto *Result = ST.Get(Map.find(Original)->second);
3739 if (Result) {
3740 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3741 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
3742 }
3743 return Result;
3744 }
3745
3746 /// Try to match PHI node to Candidate.
3747 /// Matcher tracks the matched Phi nodes.
3748 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
3750 PhiNodeSet &PhiNodesToMatch) {
3751 SmallVector<PHIPair, 8> WorkList;
3752 Matcher.insert({PHI, Candidate});
3753 SmallSet<PHINode *, 8> MatchedPHIs;
3754 MatchedPHIs.insert(PHI);
3755 WorkList.push_back({PHI, Candidate});
3756 SmallSet<PHIPair, 8> Visited;
3757 while (!WorkList.empty()) {
3758 auto Item = WorkList.pop_back_val();
3759 if (!Visited.insert(Item).second)
3760 continue;
3761 // We iterate over all incoming values to Phi to compare them.
3762 // If values are different and both of them Phi and the first one is a
3763 // Phi we added (subject to match) and both of them is in the same basic
3764 // block then we can match our pair if values match. So we state that
3765 // these values match and add it to work list to verify that.
3766 for (auto *B : Item.first->blocks()) {
3767 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3768 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3769 if (FirstValue == SecondValue)
3770 continue;
3771
3772 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3773 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3774
3775 // One of them is not Phi or
3776 // The first one is not Phi node from the set we'd like to match or
3777 // Phi nodes from different basic blocks then
3778 // we will not be able to match.
3779 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3780 FirstPhi->getParent() != SecondPhi->getParent())
3781 return false;
3782
3783 // If we already matched them then continue.
3784 if (Matcher.count({FirstPhi, SecondPhi}))
3785 continue;
3786 // So the values are different and does not match. So we need them to
3787 // match. (But we register no more than one match per PHI node, so that
3788 // we won't later try to replace them twice.)
3789 if (MatchedPHIs.insert(FirstPhi).second)
3790 Matcher.insert({FirstPhi, SecondPhi});
3791 // But me must check it.
3792 WorkList.push_back({FirstPhi, SecondPhi});
3793 }
3794 }
3795 return true;
3796 }
3797
3798 /// For the given set of PHI nodes (in the SimplificationTracker) try
3799 /// to find their equivalents.
3800 /// Returns false if this matching fails and creation of new Phi is disabled.
3801 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
3802 unsigned &PhiNotMatchedCount) {
3803 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3804 // order, so the replacements (ReplacePhi) are also done in a deterministic
3805 // order.
3807 SmallPtrSet<PHINode *, 8> WillNotMatch;
3808 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
3809 while (PhiNodesToMatch.size()) {
3810 PHINode *PHI = *PhiNodesToMatch.begin();
3811
3812 // Add us, if no Phi nodes in the basic block we do not match.
3813 WillNotMatch.clear();
3814 WillNotMatch.insert(PHI);
3815
3816 // Traverse all Phis until we found equivalent or fail to do that.
3817 bool IsMatched = false;
3818 for (auto &P : PHI->getParent()->phis()) {
3819 // Skip new Phi nodes.
3820 if (PhiNodesToMatch.count(&P))
3821 continue;
3822 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3823 break;
3824 // If it does not match, collect all Phi nodes from matcher.
3825 // if we end up with no match, them all these Phi nodes will not match
3826 // later.
3827 for (auto M : Matched)
3828 WillNotMatch.insert(M.first);
3829 Matched.clear();
3830 }
3831 if (IsMatched) {
3832 // Replace all matched values and erase them.
3833 for (auto MV : Matched)
3834 ST.ReplacePhi(MV.first, MV.second);
3835 Matched.clear();
3836 continue;
3837 }
3838 // If we are not allowed to create new nodes then bail out.
3839 if (!AllowNewPhiNodes)
3840 return false;
3841 // Just remove all seen values in matcher. They will not match anything.
3842 PhiNotMatchedCount += WillNotMatch.size();
3843 for (auto *P : WillNotMatch)
3844 PhiNodesToMatch.erase(P);
3845 }
3846 return true;
3847 }
3848 /// Fill the placeholders with values from predecessors and simplify them.
3849 void FillPlaceholders(FoldAddrToValueMapping &Map,
3850 SmallVectorImpl<Value *> &TraverseOrder,
3851 SimplificationTracker &ST) {
3852 while (!TraverseOrder.empty()) {
3853 Value *Current = TraverseOrder.pop_back_val();
3854 assert(Map.contains(Current) && "No node to fill!!!");
3855 Value *V = Map[Current];
3856
3857 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3858 // CurrentValue also must be Select.
3859 auto *CurrentSelect = cast<SelectInst>(Current);
3860 auto *TrueValue = CurrentSelect->getTrueValue();
3861 assert(Map.contains(TrueValue) && "No True Value!");
3862 Select->setTrueValue(ST.Get(Map[TrueValue]));
3863 auto *FalseValue = CurrentSelect->getFalseValue();
3864 assert(Map.contains(FalseValue) && "No False Value!");
3865 Select->setFalseValue(ST.Get(Map[FalseValue]));
3866 } else {
3867 // Must be a Phi node then.
3868 auto *PHI = cast<PHINode>(V);
3869 // Fill the Phi node with values from predecessors.
3870 for (auto *B : predecessors(PHI->getParent())) {
3871 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
3872 assert(Map.contains(PV) && "No predecessor Value!");
3873 PHI->addIncoming(ST.Get(Map[PV]), B);
3874 }
3875 }
3876 Map[Current] = ST.Simplify(V);
3877 }
3878 }
3879
3880 /// Starting from original value recursively iterates over def-use chain up to
3881 /// known ending values represented in a map. For each traversed phi/select
3882 /// inserts a placeholder Phi or Select.
3883 /// Reports all new created Phi/Select nodes by adding them to set.
3884 /// Also reports and order in what values have been traversed.
3885 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3886 SmallVectorImpl<Value *> &TraverseOrder,
3887 SimplificationTracker &ST) {
3888 SmallVector<Value *, 32> Worklist;
3889 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
3890 "Address must be a Phi or Select node");
3891 auto *Dummy = PoisonValue::get(CommonType);
3892 Worklist.push_back(Original);
3893 while (!Worklist.empty()) {
3894 Value *Current = Worklist.pop_back_val();
3895 // if it is already visited or it is an ending value then skip it.
3896 if (Map.contains(Current))
3897 continue;
3898 TraverseOrder.push_back(Current);
3899
3900 // CurrentValue must be a Phi node or select. All others must be covered
3901 // by anchors.
3902 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
3903 // Is it OK to get metadata from OrigSelect?!
3904 // Create a Select placeholder with dummy value.
3906 CurrentSelect->getCondition(), Dummy, Dummy,
3907 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
3908 Map[Current] = Select;
3909 ST.insertNewSelect(Select);
3910 // We are interested in True and False values.
3911 Worklist.push_back(CurrentSelect->getTrueValue());
3912 Worklist.push_back(CurrentSelect->getFalseValue());
3913 } else {
3914 // It must be a Phi node then.
3915 PHINode *CurrentPhi = cast<PHINode>(Current);
3916 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3917 PHINode *PHI =
3918 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
3919 Map[Current] = PHI;
3920 ST.insertNewPhi(PHI);
3921 append_range(Worklist, CurrentPhi->incoming_values());
3922 }
3923 }
3924 }
3925
3926 bool addrModeCombiningAllowed() {
3928 return false;
3929 switch (DifferentField) {
3930 default:
3931 return false;
3932 case ExtAddrMode::BaseRegField:
3934 case ExtAddrMode::BaseGVField:
3935 return AddrSinkCombineBaseGV;
3936 case ExtAddrMode::BaseOffsField:
3938 case ExtAddrMode::ScaledRegField:
3940 }
3941 }
3942};
3943} // end anonymous namespace
3944
3945/// Try adding ScaleReg*Scale to the current addressing mode.
3946/// Return true and update AddrMode if this addr mode is legal for the target,
3947/// false if not.
3948bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3949 unsigned Depth) {
3950 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3951 // mode. Just process that directly.
3952 if (Scale == 1)
3953 return matchAddr(ScaleReg, Depth);
3954
3955 // If the scale is 0, it takes nothing to add this.
3956 if (Scale == 0)
3957 return true;
3958
3959 // If we already have a scale of this value, we can add to it, otherwise, we
3960 // need an available scale field.
3961 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3962 return false;
3963
3964 ExtAddrMode TestAddrMode = AddrMode;
3965
3966 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3967 // [A+B + A*7] -> [B+A*8].
3968 TestAddrMode.Scale += Scale;
3969 TestAddrMode.ScaledReg = ScaleReg;
3970
3971 // If the new address isn't legal, bail out.
3972 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3973 return false;
3974
3975 // It was legal, so commit it.
3976 AddrMode = TestAddrMode;
3977
3978 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3979 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3980 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
3981 // go any further: we can reuse it and cannot eliminate it.
3982 ConstantInt *CI = nullptr;
3983 Value *AddLHS = nullptr;
3984 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3985 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
3986 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
3987 TestAddrMode.InBounds = false;
3988 TestAddrMode.ScaledReg = AddLHS;
3989 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
3990
3991 // If this addressing mode is legal, commit it and remember that we folded
3992 // this instruction.
3993 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3994 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3995 AddrMode = TestAddrMode;
3996 return true;
3997 }
3998 // Restore status quo.
3999 TestAddrMode = AddrMode;
4000 }
4001
4002 // If this is an add recurrence with a constant step, return the increment
4003 // instruction and the canonicalized step.
4004 auto GetConstantStep =
4005 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4006 auto *PN = dyn_cast<PHINode>(V);
4007 if (!PN)
4008 return std::nullopt;
4009 auto IVInc = getIVIncrement(PN, &LI);
4010 if (!IVInc)
4011 return std::nullopt;
4012 // TODO: The result of the intrinsics above is two-complement. However when
4013 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4014 // If it has nuw or nsw flags, we need to make sure that these flags are
4015 // inferrable at the point of memory instruction. Otherwise we are replacing
4016 // well-defined two-complement computation with poison. Currently, to avoid
4017 // potentially complex analysis needed to prove this, we reject such cases.
4018 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4019 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4020 return std::nullopt;
4021 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4022 return std::make_pair(IVInc->first, ConstantStep->getValue());
4023 return std::nullopt;
4024 };
4025
4026 // Try to account for the following special case:
4027 // 1. ScaleReg is an inductive variable;
4028 // 2. We use it with non-zero offset;
4029 // 3. IV's increment is available at the point of memory instruction.
4030 //
4031 // In this case, we may reuse the IV increment instead of the IV Phi to
4032 // achieve the following advantages:
4033 // 1. If IV step matches the offset, we will have no need in the offset;
4034 // 2. Even if they don't match, we will reduce the overlap of living IV
4035 // and IV increment, that will potentially lead to better register
4036 // assignment.
4037 if (AddrMode.BaseOffs) {
4038 if (auto IVStep = GetConstantStep(ScaleReg)) {
4039 Instruction *IVInc = IVStep->first;
4040 // The following assert is important to ensure a lack of infinite loops.
4041 // This transforms is (intentionally) the inverse of the one just above.
4042 // If they don't agree on the definition of an increment, we'd alternate
4043 // back and forth indefinitely.
4044 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4045 APInt Step = IVStep->second;
4046 APInt Offset = Step * AddrMode.Scale;
4047 if (Offset.isSignedIntN(64)) {
4048 TestAddrMode.InBounds = false;
4049 TestAddrMode.ScaledReg = IVInc;
4050 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4051 // If this addressing mode is legal, commit it..
4052 // (Note that we defer the (expensive) domtree base legality check
4053 // to the very last possible point.)
4054 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4055 getDTFn().dominates(IVInc, MemoryInst)) {
4056 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4057 AddrMode = TestAddrMode;
4058 return true;
4059 }
4060 // Restore status quo.
4061 TestAddrMode = AddrMode;
4062 }
4063 }
4064 }
4065
4066 // Otherwise, just return what we have.
4067 return true;
4068}
4069
4070/// This is a little filter, which returns true if an addressing computation
4071/// involving I might be folded into a load/store accessing it.
4072/// This doesn't need to be perfect, but needs to accept at least
4073/// the set of instructions that MatchOperationAddr can.
4075 switch (I->getOpcode()) {
4076 case Instruction::BitCast:
4077 case Instruction::AddrSpaceCast:
4078 // Don't touch identity bitcasts.
4079 if (I->getType() == I->getOperand(0)->getType())
4080 return false;
4081 return I->getType()->isIntOrPtrTy();
4082 case Instruction::PtrToInt:
4083 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4084 return true;
4085 case Instruction::IntToPtr:
4086 // We know the input is intptr_t, so this is foldable.
4087 return true;
4088 case Instruction::Add:
4089 return true;
4090 case Instruction::Mul:
4091 case Instruction::Shl:
4092 // Can only handle X*C and X << C.
4093 return isa<ConstantInt>(I->getOperand(1));
4094 case Instruction::GetElementPtr:
4095 return true;
4096 default:
4097 return false;
4098 }
4099}
4100
4101/// Check whether or not \p Val is a legal instruction for \p TLI.
4102/// \note \p Val is assumed to be the product of some type promotion.
4103/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4104/// to be legal, as the non-promoted value would have had the same state.
4106 const DataLayout &DL, Value *Val) {
4107 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4108 if (!PromotedInst)
4109 return false;
4110 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4111 // If the ISDOpcode is undefined, it was undefined before the promotion.
4112 if (!ISDOpcode)
4113 return true;
4114 // Otherwise, check if the promoted instruction is legal or not.
4115 return TLI.isOperationLegalOrCustom(
4116 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4117}
4118
4119namespace {
4120
4121/// Hepler class to perform type promotion.
4122class TypePromotionHelper {
4123 /// Utility function to add a promoted instruction \p ExtOpnd to
4124 /// \p PromotedInsts and record the type of extension we have seen.
4125 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4126 Instruction *ExtOpnd, bool IsSExt) {
4127 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4128 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
4129 if (It != PromotedInsts.end()) {
4130 // If the new extension is same as original, the information in
4131 // PromotedInsts[ExtOpnd] is still correct.
4132 if (It->second.getInt() == ExtTy)
4133 return;
4134
4135 // Now the new extension is different from old extension, we make
4136 // the type information invalid by setting extension type to
4137 // BothExtension.
4138 ExtTy = BothExtension;
4139 }
4140 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4141 }
4142
4143 /// Utility function to query the original type of instruction \p Opnd
4144 /// with a matched extension type. If the extension doesn't match, we
4145 /// cannot use the information we had on the original type.
4146 /// BothExtension doesn't match any extension type.
4147 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4148 Instruction *Opnd, bool IsSExt) {
4149 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4150 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4151 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4152 return It->second.getPointer();
4153 return nullptr;
4154 }
4155
4156 /// Utility function to check whether or not a sign or zero extension
4157 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4158 /// either using the operands of \p Inst or promoting \p Inst.
4159 /// The type of the extension is defined by \p IsSExt.
4160 /// In other words, check if:
4161 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4162 /// #1 Promotion applies:
4163 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4164 /// #2 Operand reuses:
4165 /// ext opnd1 to ConsideredExtType.
4166 /// \p PromotedInsts maps the instructions to their type before promotion.
4167 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4168 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4169
4170 /// Utility function to determine if \p OpIdx should be promoted when
4171 /// promoting \p Inst.
4172 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4173 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4174 }
4175
4176 /// Utility function to promote the operand of \p Ext when this
4177 /// operand is a promotable trunc or sext or zext.
4178 /// \p PromotedInsts maps the instructions to their type before promotion.
4179 /// \p CreatedInstsCost[out] contains the cost of all instructions
4180 /// created to promote the operand of Ext.
4181 /// Newly added extensions are inserted in \p Exts.
4182 /// Newly added truncates are inserted in \p Truncs.
4183 /// Should never be called directly.
4184 /// \return The promoted value which is used instead of Ext.
4185 static Value *promoteOperandForTruncAndAnyExt(
4186 Instruction *Ext, TypePromotionTransaction &TPT,
4187 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4190
4191 /// Utility function to promote the operand of \p Ext when this
4192 /// operand is promotable and is not a supported trunc or sext.
4193 /// \p PromotedInsts maps the instructions to their type before promotion.
4194 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4195 /// created to promote the operand of Ext.
4196 /// Newly added extensions are inserted in \p Exts.
4197 /// Newly added truncates are inserted in \p Truncs.
4198 /// Should never be called directly.
4199 /// \return The promoted value which is used instead of Ext.
4200 static Value *promoteOperandForOther(Instruction *Ext,
4201 TypePromotionTransaction &TPT,
4202 InstrToOrigTy &PromotedInsts,
4203 unsigned &CreatedInstsCost,
4206 const TargetLowering &TLI, bool IsSExt);
4207
4208 /// \see promoteOperandForOther.
4209 static Value *signExtendOperandForOther(
4210 Instruction *Ext, TypePromotionTransaction &TPT,
4211 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4213 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4214 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4215 Exts, Truncs, TLI, true);
4216 }
4217
4218 /// \see promoteOperandForOther.
4219 static Value *zeroExtendOperandForOther(
4220 Instruction *Ext, TypePromotionTransaction &TPT,
4221 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4223 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4224 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4225 Exts, Truncs, TLI, false);
4226 }
4227
4228public:
4229 /// Type for the utility function that promotes the operand of Ext.
4230 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4231 InstrToOrigTy &PromotedInsts,
4232 unsigned &CreatedInstsCost,
4235 const TargetLowering &TLI);
4236
4237 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4238 /// action to promote the operand of \p Ext instead of using Ext.
4239 /// \return NULL if no promotable action is possible with the current
4240 /// sign extension.
4241 /// \p InsertedInsts keeps track of all the instructions inserted by the
4242 /// other CodeGenPrepare optimizations. This information is important
4243 /// because we do not want to promote these instructions as CodeGenPrepare
4244 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4245 /// \p PromotedInsts maps the instructions to their type before promotion.
4246 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4247 const TargetLowering &TLI,
4248 const InstrToOrigTy &PromotedInsts);
4249};
4250
4251} // end anonymous namespace
4252
4253bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4254 Type *ConsideredExtType,
4255 const InstrToOrigTy &PromotedInsts,
4256 bool IsSExt) {
4257 // The promotion helper does not know how to deal with vector types yet.
4258 // To be able to fix that, we would need to fix the places where we
4259 // statically extend, e.g., constants and such.
4260 if (Inst->getType()->isVectorTy())
4261 return false;
4262
4263 // We can always get through zext.
4264 if (isa<ZExtInst>(Inst))
4265 return true;
4266
4267 // sext(sext) is ok too.
4268 if (IsSExt && isa<SExtInst>(Inst))
4269 return true;
4270
4271 // We can get through binary operator, if it is legal. In other words, the
4272 // binary operator must have a nuw or nsw flag.
4273 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4274 if (isa<OverflowingBinaryOperator>(BinOp) &&
4275 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4276 (IsSExt && BinOp->hasNoSignedWrap())))
4277 return true;
4278
4279 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4280 if ((Inst->getOpcode() == Instruction::And ||
4281 Inst->getOpcode() == Instruction::Or))
4282 return true;
4283
4284 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4285 if (Inst->getOpcode() == Instruction::Xor) {
4286 // Make sure it is not a NOT.
4287 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4288 if (!Cst->getValue().isAllOnes())
4289 return true;
4290 }
4291
4292 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4293 // It may change a poisoned value into a regular value, like
4294 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4295 // poisoned value regular value
4296 // It should be OK since undef covers valid value.
4297 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4298 return true;
4299
4300 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4301 // It may change a poisoned value into a regular value, like
4302 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4303 // poisoned value regular value
4304 // It should be OK since undef covers valid value.
4305 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4306 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4307 if (ExtInst->hasOneUse()) {
4308 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4309 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4310 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4311 if (Cst &&
4312 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4313 return true;
4314 }
4315 }
4316 }
4317
4318 // Check if we can do the following simplification.
4319 // ext(trunc(opnd)) --> ext(opnd)
4320 if (!isa<TruncInst>(Inst))
4321 return false;
4322
4323 Value *OpndVal = Inst->getOperand(0);
4324 // Check if we can use this operand in the extension.
4325 // If the type is larger than the result type of the extension, we cannot.
4326 if (!OpndVal->getType()->isIntegerTy() ||
4327 OpndVal->getType()->getIntegerBitWidth() >
4328 ConsideredExtType->getIntegerBitWidth())
4329 return false;
4330
4331 // If the operand of the truncate is not an instruction, we will not have
4332 // any information on the dropped bits.
4333 // (Actually we could for constant but it is not worth the extra logic).
4334 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4335 if (!Opnd)
4336 return false;
4337
4338 // Check if the source of the type is narrow enough.
4339 // I.e., check that trunc just drops extended bits of the same kind of
4340 // the extension.
4341 // #1 get the type of the operand and check the kind of the extended bits.
4342 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4343 if (OpndType)
4344 ;
4345 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4346 OpndType = Opnd->getOperand(0)->getType();
4347 else
4348 return false;
4349
4350 // #2 check that the truncate just drops extended bits.
4351 return Inst->getType()->getIntegerBitWidth() >=
4352 OpndType->getIntegerBitWidth();
4353}
4354
4355TypePromotionHelper::Action TypePromotionHelper::getAction(
4356 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4357 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4358 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4359 "Unexpected instruction type");
4360 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4361 Type *ExtTy = Ext->getType();
4362 bool IsSExt = isa<SExtInst>(Ext);
4363 // If the operand of the extension is not an instruction, we cannot
4364 // get through.
4365 // If it, check we can get through.
4366 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4367 return nullptr;
4368
4369 // Do not promote if the operand has been added by codegenprepare.
4370 // Otherwise, it means we are undoing an optimization that is likely to be
4371 // redone, thus causing potential infinite loop.
4372 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4373 return nullptr;
4374
4375 // SExt or Trunc instructions.
4376 // Return the related handler.
4377 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4378 isa<ZExtInst>(ExtOpnd))
4379 return promoteOperandForTruncAndAnyExt;
4380
4381 // Regular instruction.
4382 // Abort early if we will have to insert non-free instructions.
4383 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4384 return nullptr;
4385 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4386}
4387
4388Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4389 Instruction *SExt, TypePromotionTransaction &TPT,
4390 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4392 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4393 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4394 // get through it and this method should not be called.
4395 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4396 Value *ExtVal = SExt;
4397 bool HasMergedNonFreeExt = false;
4398 if (isa<ZExtInst>(SExtOpnd)) {
4399 // Replace s|zext(zext(opnd))
4400 // => zext(opnd).
4401 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4402 Value *ZExt =
4403 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4404 TPT.replaceAllUsesWith(SExt, ZExt);
4405 TPT.eraseInstruction(SExt);
4406 ExtVal = ZExt;
4407 } else {
4408 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4409 // => z|sext(opnd).
4410 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4411 }
4412 CreatedInstsCost = 0;
4413
4414 // Remove dead code.
4415 if (SExtOpnd->use_empty())
4416 TPT.eraseInstruction(SExtOpnd);
4417
4418 // Check if the extension is still needed.
4419 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4420 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4421 if (ExtInst) {
4422 if (Exts)
4423 Exts->push_back(ExtInst);
4424 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4425 }
4426 return ExtVal;
4427 }
4428
4429 // At this point we have: ext ty opnd to ty.
4430 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4431 Value *NextVal = ExtInst->getOperand(0);
4432 TPT.eraseInstruction(ExtInst, NextVal);
4433 return NextVal;
4434}
4435
4436Value *TypePromotionHelper::promoteOperandForOther(
4437 Instruction *Ext, TypePromotionTransaction &TPT,
4438 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4441 bool IsSExt) {
4442 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4443 // get through it and this method should not be called.
4444 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4445 CreatedInstsCost = 0;
4446 if (!ExtOpnd->hasOneUse()) {
4447 // ExtOpnd will be promoted.
4448 // All its uses, but Ext, will need to use a truncated value of the
4449 // promoted version.
4450 // Create the truncate now.
4451 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4452 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4453 // Insert it just after the definition.
4454 ITrunc->moveAfter(ExtOpnd);
4455 if (Truncs)
4456 Truncs->push_back(ITrunc);
4457 }
4458
4459 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4460 // Restore the operand of Ext (which has been replaced by the previous call
4461 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4462 TPT.setOperand(Ext, 0, ExtOpnd);
4463 }
4464
4465 // Get through the Instruction:
4466 // 1. Update its type.
4467 // 2. Replace the uses of Ext by Inst.
4468 // 3. Extend each operand that needs to be extended.
4469
4470 // Remember the original type of the instruction before promotion.
4471 // This is useful to know that the high bits are sign extended bits.
4472 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4473 // Step #1.
4474 TPT.mutateType(ExtOpnd, Ext->getType());
4475 // Step #2.
4476 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4477 // Step #3.
4478 Instruction *ExtForOpnd = Ext;
4479
4480 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
4481 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4482 ++OpIdx) {
4483 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4484 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4485 !shouldExtOperand(ExtOpnd, OpIdx)) {
4486 LLVM_DEBUG(dbgs() << "No need to propagate\n");
4487 continue;
4488 }
4489 // Check if we can statically extend the operand.
4490 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4491 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4492 LLVM_DEBUG(dbgs() << "Statically extend\n");
4493 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4494 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4495 : Cst->getValue().zext(BitWidth);
4496 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4497 continue;
4498 }
4499 // UndefValue are typed, so we have to statically sign extend them.
4500 if (isa<UndefValue>(Opnd)) {
4501 LLVM_DEBUG(dbgs() << "Statically extend\n");
4502 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4503 continue;
4504 }
4505
4506 // Otherwise we have to explicitly sign extend the operand.
4507 // Check if Ext was reused to extend an operand.
4508 if (!ExtForOpnd) {
4509 // If yes, create a new one.
4510 LLVM_DEBUG(dbgs() << "More operands to ext\n");
4511 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4512 : TPT.createZExt(Ext, Opnd, Ext->getType());
4513 if (!isa<Instruction>(ValForExtOpnd)) {
4514 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4515 continue;
4516 }
4517 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4518 }
4519 if (Exts)
4520 Exts->push_back(ExtForOpnd);
4521 TPT.setOperand(ExtForOpnd, 0, Opnd);
4522
4523 // Move the sign extension before the insertion point.
4524 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4525 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4526 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
4527 // If more sext are required, new instructions will have to be created.
4528 ExtForOpnd = nullptr;
4529 }
4530 if (ExtForOpnd == Ext) {
4531 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
4532 TPT.eraseInstruction(Ext);
4533 }
4534 return ExtOpnd;
4535}
4536
4537/// Check whether or not promoting an instruction to a wider type is profitable.
4538/// \p NewCost gives the cost of extension instructions created by the
4539/// promotion.
4540/// \p OldCost gives the cost of extension instructions before the promotion
4541/// plus the number of instructions that have been
4542/// matched in the addressing mode the promotion.
4543/// \p PromotedOperand is the value that has been promoted.
4544/// \return True if the promotion is profitable, false otherwise.
4545bool AddressingModeMatcher::isPromotionProfitable(
4546 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4547 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
4548 << '\n');
4549 // The cost of the new extensions is greater than the cost of the
4550 // old extension plus what we folded.
4551 // This is not profitable.
4552 if (NewCost > OldCost)
4553 return false;
4554 if (NewCost < OldCost)
4555 return true;
4556 // The promotion is neutral but it may help folding the sign extension in
4557 // loads for instance.
4558 // Check that we did not create an illegal instruction.
4559 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4560}
4561
4562/// Given an instruction or constant expr, see if we can fold the operation
4563/// into the addressing mode. If so, update the addressing mode and return
4564/// true, otherwise return false without modifying AddrMode.
4565/// If \p MovedAway is not NULL, it contains the information of whether or
4566/// not AddrInst has to be folded into the addressing mode on success.
4567/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4568/// because it has been moved away.
4569/// Thus AddrInst must not be added in the matched instructions.
4570/// This state can happen when AddrInst is a sext, since it may be moved away.
4571/// Therefore, AddrInst may not be valid when MovedAway is true and it must
4572/// not be referenced anymore.
4573bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4574 unsigned Depth,
4575 bool *MovedAway) {
4576 // Avoid exponential behavior on extremely deep expression trees.
4577 if (Depth >= 5)
4578 return false;
4579
4580 // By default, all matched instructions stay in place.
4581 if (MovedAway)
4582 *MovedAway = false;
4583
4584 switch (Opcode) {
4585 case Instruction::PtrToInt:
4586 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4587 return matchAddr(AddrInst->getOperand(0), Depth);
4588 case Instruction::IntToPtr: {
4589 auto AS = AddrInst->getType()->getPointerAddressSpace();
4590 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4591 // This inttoptr is a no-op if the integer type is pointer sized.
4592 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4593 return matchAddr(AddrInst->getOperand(0), Depth);
4594 return false;
4595 }
4596 case Instruction::BitCast:
4597 // BitCast is always a noop, and we can handle it as long as it is
4598 // int->int or pointer->pointer (we don't want int<->fp or something).
4599 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
4600 // Don't touch identity bitcasts. These were probably put here by LSR,
4601 // and we don't want to mess around with them. Assume it knows what it
4602 // is doing.
4603 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4604 return matchAddr(AddrInst->getOperand(0), Depth);
4605 return false;
4606 case Instruction::AddrSpaceCast: {
4607 unsigned SrcAS =
4608 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4609 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4610 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
4611 return matchAddr(AddrInst->getOperand(0), Depth);
4612 return false;
4613 }
4614 case Instruction::Add: {
4615 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4616 ExtAddrMode BackupAddrMode = AddrMode;
4617 unsigned OldSize = AddrModeInsts.size();
4618 // Start a transaction at this point.
4619 // The LHS may match but not the RHS.
4620 // Therefore, we need a higher level restoration point to undo partially
4621 // matched operation.
4622 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4623 TPT.getRestorationPoint();
4624
4625 AddrMode.InBounds = false;
4626 if (matchAddr(AddrInst->getOperand(1), Depth + 1) &&
4627 matchAddr(AddrInst->getOperand(0), Depth + 1))
4628 return true;
4629
4630 // Restore the old addr mode info.
4631 AddrMode = BackupAddrMode;
4632 AddrModeInsts.resize(OldSize);
4633 TPT.rollback(LastKnownGood);
4634
4635 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
4636 if (matchAddr(AddrInst->getOperand(0), Depth + 1) &&
4637 matchAddr(AddrInst->getOperand(1), Depth + 1))
4638 return true;
4639
4640 // Otherwise we definitely can't merge the ADD in.
4641 AddrMode = BackupAddrMode;
4642 AddrModeInsts.resize(OldSize);
4643 TPT.rollback(LastKnownGood);
4644 break;
4645 }
4646 // case Instruction::Or:
4647 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4648 // break;
4649 case Instruction::Mul:
4650 case Instruction::Shl: {
4651 // Can only handle X*C and X << C.
4652 AddrMode.InBounds = false;
4653 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4654 if (!RHS || RHS->getBitWidth() > 64)
4655 return false;
4656 int64_t Scale = Opcode == Instruction::Shl
4657 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
4658 : RHS->getSExtValue();
4659
4660 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4661 }
4662 case Instruction::GetElementPtr: {
4663 // Scan the GEP. We check it if it contains constant offsets and at most
4664 // one variable offset.
4665 int VariableOperand = -1;
4666 unsigned VariableScale = 0;
4667
4668 int64_t ConstantOffset = 0;
4669 gep_type_iterator GTI = gep_type_begin(AddrInst);
4670 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4671 if (StructType *STy = GTI.getStructTypeOrNull()) {
4672 const StructLayout *SL = DL.getStructLayout(STy);
4673 unsigned Idx =
4674 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4675 ConstantOffset += SL->getElementOffset(Idx);
4676 } else {
4677 TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType());
4678 if (TS.isNonZero()) {
4679 // The optimisations below currently only work for fixed offsets.
4680 if (TS.isScalable())
4681 return false;
4682 int64_t TypeSize = TS.getFixedValue();
4683 if (ConstantInt *CI =
4684 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4685 const APInt &CVal = CI->getValue();
4686 if (CVal.getSignificantBits() <= 64) {
4687 ConstantOffset += CVal.getSExtValue() * TypeSize;
4688 continue;
4689 }
4690 }
4691 // We only allow one variable index at the moment.
4692 if (VariableOperand != -1)
4693 return false;
4694
4695 // Remember the variable index.
4696 VariableOperand = i;
4697 VariableScale = TypeSize;
4698 }
4699 }
4700 }
4701
4702 // A common case is for the GEP to only do a constant offset. In this case,
4703 // just add it to the disp field and check validity.
4704 if (VariableOperand == -1) {
4705 AddrMode.BaseOffs += ConstantOffset;
4706 if (ConstantOffset == 0 ||
4707 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4708 // Check to see if we can fold the base pointer in too.
4709 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
4710 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4711 AddrMode.InBounds = false;
4712 return true;
4713 }
4714 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4715 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4716 ConstantOffset > 0) {
4717 // Record GEPs with non-zero offsets as candidates for splitting in the
4718 // event that the offset cannot fit into the r+i addressing mode.
4719 // Simple and common case that only one GEP is used in calculating the
4720 // address for the memory access.
4721 Value *Base = AddrInst->getOperand(0);
4722 auto *BaseI = dyn_cast<Instruction>(Base);
4723 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4724 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4725 (BaseI && !isa<CastInst>(BaseI) &&
4726 !isa<GetElementPtrInst>(BaseI))) {
4727 // Make sure the parent block allows inserting non-PHI instructions
4728 // before the terminator.
4729 BasicBlock *Parent =
4730 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4731 if (!Parent->getTerminator()->isEHPad())
4732 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4733 }
4734 }
4735 AddrMode.BaseOffs -= ConstantOffset;
4736 return false;
4737 }
4738
4739 // Save the valid addressing mode in case we can't match.
4740 ExtAddrMode BackupAddrMode = AddrMode;
4741 unsigned OldSize = AddrModeInsts.size();
4742
4743 // See if the scale and offset amount is valid for this target.
4744 AddrMode.BaseOffs += ConstantOffset;
4745 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4746 AddrMode.InBounds = false;
4747
4748 // Match the base operand of the GEP.
4749 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
4750 // If it couldn't be matched, just stuff the value in a register.
4751 if (AddrMode.HasBaseReg) {
4752 AddrMode = BackupAddrMode;
4753 AddrModeInsts.resize(OldSize);
4754 return false;
4755 }
4756 AddrMode.HasBaseReg = true;
4757 AddrMode.BaseReg = AddrInst->getOperand(0);
4758 }
4759
4760 // Match the remaining variable portion of the GEP.
4761 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4762 Depth)) {
4763 // If it couldn't be matched, try stuffing the base into a register
4764 // instead of matching it, and retrying the match of the scale.
4765 AddrMode = BackupAddrMode;
4766 AddrModeInsts.resize(OldSize);
4767 if (AddrMode.HasBaseReg)
4768 return false;
4769 AddrMode.HasBaseReg = true;
4770 AddrMode.BaseReg = AddrInst->getOperand(0);
4771 AddrMode.BaseOffs += ConstantOffset;
4772 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4773 VariableScale, Depth)) {
4774 // If even that didn't work, bail.
4775 AddrMode = BackupAddrMode;
4776 AddrModeInsts.resize(OldSize);
4777 return false;
4778 }
4779 }
4780
4781 return true;
4782 }
4783 case Instruction::SExt:
4784 case Instruction::ZExt: {
4785 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4786 if (!Ext)
4787 return false;
4788
4789 // Try to move this ext out of the way of the addressing mode.
4790 // Ask for a method for doing so.
4791 TypePromotionHelper::Action TPH =
4792 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4793 if (!TPH)
4794 return false;
4795
4796 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4797 TPT.getRestorationPoint();
4798 unsigned CreatedInstsCost = 0;
4799 unsigned ExtCost = !TLI.isExtFree(Ext);
4800 Value *PromotedOperand =
4801 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4802 // SExt has been moved away.
4803 // Thus either it will be rematched later in the recursive calls or it is
4804 // gone. Anyway, we must not fold it into the addressing mode at this point.
4805 // E.g.,
4806 // op = add opnd, 1
4807 // idx = ext op
4808 // addr = gep base, idx
4809 // is now:
4810 // promotedOpnd = ext opnd <- no match here
4811 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4812 // addr = gep base, op <- match
4813 if (MovedAway)
4814 *MovedAway = true;
4815
4816 assert(PromotedOperand &&
4817 "TypePromotionHelper should have filtered out those cases");
4818
4819 ExtAddrMode BackupAddrMode = AddrMode;
4820 unsigned OldSize = AddrModeInsts.size();
4821
4822 if (!matchAddr(PromotedOperand, Depth) ||
4823 // The total of the new cost is equal to the cost of the created
4824 // instructions.
4825 // The total of the old cost is equal to the cost of the extension plus
4826 // what we have saved in the addressing mode.
4827 !isPromotionProfitable(CreatedInstsCost,
4828 ExtCost + (AddrModeInsts.size() - OldSize),
4829 PromotedOperand)) {
4830 AddrMode = BackupAddrMode;
4831 AddrModeInsts.resize(OldSize);
4832 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
4833 TPT.rollback(LastKnownGood);
4834 return false;
4835 }
4836 return true;
4837 }
4838 }
4839 return false;
4840}
4841
4842/// If we can, try to add the value of 'Addr' into the current addressing mode.
4843/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4844/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4845/// for the target.
4846///
4847bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4848 // Start a transaction at this point that we will rollback if the matching
4849 // fails.
4850 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4851 TPT.getRestorationPoint();
4852 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4853 if (CI->getValue().isSignedIntN(64)) {
4854 // Fold in immediates if legal for the target.
4855 AddrMode.BaseOffs += CI->getSExtValue();
4856 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4857 return true;
4858 AddrMode.BaseOffs -= CI->getSExtValue();
4859 }
4860 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4861 // If this is a global variable, try to fold it into the addressing mode.
4862 if (!AddrMode.BaseGV) {
4863 AddrMode.BaseGV = GV;
4864 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4865 return true;
4866 AddrMode.BaseGV = nullptr;
4867 }
4868 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4869 ExtAddrMode BackupAddrMode = AddrMode;
4870 unsigned OldSize = AddrModeInsts.size();
4871
4872 // Check to see if it is possible to fold this operation.
4873 bool MovedAway = false;
4874 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4875 // This instruction may have been moved away. If so, there is nothing
4876 // to check here.
4877 if (MovedAway)
4878 return true;
4879 // Okay, it's possible to fold this. Check to see if it is actually
4880 // *profitable* to do so. We use a simple cost model to avoid increasing
4881 // register pressure too much.
4882 if (I->hasOneUse() ||
4883 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4884 AddrModeInsts.push_back(I);
4885 return true;
4886 }
4887
4888 // It isn't profitable to do this, roll back.
4889 AddrMode = BackupAddrMode;
4890 AddrModeInsts.resize(OldSize);
4891 TPT.rollback(LastKnownGood);
4892 }
4893 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4894 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4895 return true;
4896 TPT.rollback(LastKnownGood);
4897 } else if (isa<ConstantPointerNull>(Addr)) {
4898 // Null pointer gets folded without affecting the addressing mode.
4899 return true;
4900 }
4901
4902 // Worse case, the target should support [reg] addressing modes. :)
4903 if (!AddrMode.HasBaseReg) {
4904 AddrMode.HasBaseReg = true;
4905 AddrMode.BaseReg = Addr;
4906 // Still check for legality in case the target supports [imm] but not [i+r].
4907 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4908 return true;
4909 AddrMode.HasBaseReg = false;
4910 AddrMode.BaseReg = nullptr;
4911 }
4912
4913 // If the base register is already taken, see if we can do [r+r].
4914 if (AddrMode.Scale == 0) {
4915 AddrMode.Scale = 1;
4916 AddrMode.ScaledReg = Addr;
4917 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4918 return true;
4919 AddrMode.Scale = 0;
4920 AddrMode.ScaledReg = nullptr;
4921 }
4922 // Couldn't match.
4923 TPT.rollback(LastKnownGood);
4924 return false;
4925}
4926
4927/// Check to see if all uses of OpVal by the specified inline asm call are due
4928/// to memory operands. If so, return true, otherwise return false.
4930 const TargetLowering &TLI,
4931 const TargetRegisterInfo &TRI) {
4932 const Function *F = CI->getFunction();
4933 TargetLowering::AsmOperandInfoVector TargetConstraints =
4934 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI);
4935
4936 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
4937 // Compute the constraint code and ConstraintType to use.
4938 TLI.ComputeConstraintToUse(OpInfo, SDValue());
4939
4940 // If this asm operand is our Value*, and if it isn't an indirect memory
4941 // operand, we can't fold it! TODO: Also handle C_Address?
4942 if (OpInfo.CallOperandVal == OpVal &&
4943 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4944 !OpInfo.isIndirect))
4945 return false;
4946 }
4947
4948 return true;
4949}
4950
4951// Max number of memory uses to look at before aborting the search to conserve
4952// compile time.
4953static constexpr int MaxMemoryUsesToScan = 20;
4954
4955/// Recursively walk all the uses of I until we find a memory use.
4956/// If we find an obviously non-foldable instruction, return true.
4957/// Add accessed addresses and types to MemoryUses.
4959 Instruction *I, SmallVectorImpl<std::pair<Value *, Type *>> &MemoryUses,
4960 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4961 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
4962 BlockFrequencyInfo *BFI, int SeenInsts = 0) {
4963 // If we already considered this instruction, we're done.
4964 if (!ConsideredInsts.insert(I).second)
4965 return false;
4966
4967 // If this is an obviously unfoldable instruction, bail out.
4968 if (!MightBeFoldableInst(I))
4969 return true;
4970
4971 // Loop over all the uses, recursively processing them.
4972 for (Use &U : I->uses()) {
4973 // Conservatively return true if we're seeing a large number or a deep chain
4974 // of users. This avoids excessive compilation times in pathological cases.
4975 if (SeenInsts++ >= MaxMemoryUsesToScan)
4976 return true;
4977
4978 Instruction *UserI = cast<Instruction>(U.getUser());
4979 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4980 MemoryUses.push_back({U.get(), LI->getType()});
4981 continue;
4982 }
4983
4984 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4985 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
4986 return true; // Storing addr, not into addr.
4987 MemoryUses.push_back({U.get(), SI->getValueOperand()->getType()});
4988 continue;
4989 }
4990
4991 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4992 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
4993 return true; // Storing addr, not into addr.
4994 MemoryUses.push_back({U.get(), RMW->getValOperand()->getType()});
4995 continue;
4996 }
4997
4998 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4999 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5000 return true; // Storing addr, not into addr.
5001 MemoryUses.push_back({U.get(), CmpX->getCompareOperand()->getType()});
5002 continue;
5003 }
5004
5005 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5006 if (CI->hasFnAttr(Attribute::Cold)) {
5007 // If this is a cold call, we can sink the addressing calculation into
5008 // the cold path. See optimizeCallInst
5009 bool OptForSize =
5010 OptSize || llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
5011 if (!OptForSize)
5012 continue;
5013 }
5014
5015 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5016 if (!IA)
5017 return true;
5018
5019 // If this is a memory operand, we're cool, otherwise bail out.
5020 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5021 return true;
5022 continue;
5023 }
5024
5025 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5026 PSI, BFI, SeenInsts))
5027 return true;
5028 }
5029
5030 return false;
5031}
5032
5033/// Return true if Val is already known to be live at the use site that we're
5034/// folding it into. If so, there is no cost to include it in the addressing
5035/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5036/// instruction already.
5037bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5038 Value *KnownLive1,
5039 Value *KnownLive2) {
5040 // If Val is either of the known-live values, we know it is live!
5041 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5042 return true;
5043
5044 // All values other than instructions and arguments (e.g. constants) are live.
5045 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5046 return true;
5047
5048 // If Val is a constant sized alloca in the entry block, it is live, this is
5049 // true because it is just a reference to the stack/frame pointer, which is
5050 // live for the whole function.
5051 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5052 if (AI->isStaticAlloca())
5053 return true;
5054
5055 // Check to see if this value is already used in the memory instruction's
5056 // block. If so, it's already live into the block at the very least, so we
5057 // can reasonably fold it.
5058 return Val->isUsedInBasicBlock(MemoryInst->getParent());
5059}
5060
5061/// It is possible for the addressing mode of the machine to fold the specified
5062/// instruction into a load or store that ultimately uses it.
5063/// However, the specified instruction has multiple uses.
5064/// Given this, it may actually increase register pressure to fold it
5065/// into the load. For example, consider this code:
5066///
5067/// X = ...
5068/// Y = X+1
5069/// use(Y) -> nonload/store
5070/// Z = Y+1
5071/// load Z
5072///
5073/// In this case, Y has multiple uses, and can be folded into the load of Z
5074/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5075/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5076/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5077/// number of computations either.
5078///
5079/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5080/// X was live across 'load Z' for other reasons, we actually *would* want to
5081/// fold the addressing mode in the Z case. This would make Y die earlier.
5082bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5083 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5084 if (IgnoreProfitability)
5085 return true;
5086
5087 // AMBefore is the addressing mode before this instruction was folded into it,
5088 // and AMAfter is the addressing mode after the instruction was folded. Get
5089 // the set of registers referenced by AMAfter and subtract out those
5090 // referenced by AMBefore: this is the set of values which folding in this
5091 // address extends the lifetime of.
5092 //
5093 // Note that there are only two potential values being referenced here,
5094 // BaseReg and ScaleReg (global addresses are always available, as are any
5095 // folded immediates).
5096 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5097
5098 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5099 // lifetime wasn't extended by adding this instruction.
5100 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5101 BaseReg = nullptr;
5102 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5103 ScaledReg = nullptr;
5104
5105 // If folding this instruction (and it's subexprs) didn't extend any live
5106 // ranges, we're ok with it.
5107 if (!BaseReg && !ScaledReg)
5108 return true;
5109
5110 // If all uses of this instruction can have the address mode sunk into them,
5111 // we can remove the addressing mode and effectively trade one live register
5112 // for another (at worst.) In this context, folding an addressing mode into
5113 // the use is just a particularly nice way of sinking it.
5115 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5116 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, PSI,
5117 BFI))
5118 return false; // Has a non-memory, non-foldable use!
5119
5120 // Now that we know that all uses of this instruction are part of a chain of
5121 // computation involving only operations that could theoretically be folded
5122 // into a memory use, loop over each of these memory operation uses and see
5123 // if they could *actually* fold the instruction. The assumption is that
5124 // addressing modes are cheap and that duplicating the computation involved
5125 // many times is worthwhile, even on a fastpath. For sinking candidates
5126 // (i.e. cold call sites), this serves as a way to prevent excessive code
5127 // growth since most architectures have some reasonable small and fast way to
5128 // compute an effective address. (i.e LEA on x86)
5129 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5130 for (const std::pair<Value *, Type *> &Pair : MemoryUses) {
5131 Value *Address = Pair.first;
5132 Type *AddressAccessTy = Pair.second;
5133 unsigned AS = Address->getType()->getPointerAddressSpace();
5134
5135 // Do a match against the root of this address, ignoring profitability. This
5136 // will tell us if the addressing mode for the memory operation will
5137 // *actually* cover the shared instruction.
5139 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5140 0);
5141 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5142 TPT.getRestorationPoint();
5143 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5144 AddressAccessTy, AS, MemoryInst, Result,
5145 InsertedInsts, PromotedInsts, TPT,
5146 LargeOffsetGEP, OptSize, PSI, BFI);
5147 Matcher.IgnoreProfitability = true;
5148 bool Success = Matcher.matchAddr(Address, 0);
5149 (void)Success;
5150 assert(Success && "Couldn't select *anything*?");
5151
5152 // The match was to check the profitability, the changes made are not
5153 // part of the original matcher. Therefore, they should be dropped
5154 // otherwise the original matcher will not present the right state.
5155 TPT.rollback(LastKnownGood);
5156
5157 // If the match didn't cover I, then it won't be shared by it.
5158 if (!is_contained(MatchedAddrModeInsts, I))
5159 return false;
5160
5161 MatchedAddrModeInsts.clear();
5162 }
5163
5164 return true;
5165}
5166
5167/// Return true if the specified values are defined in a
5168/// different basic block than BB.
5169static bool IsNonLocalValue(Value *V, BasicBlock *BB) {