[CodeGenPrepare] Handle all debug calls in dupRetToEnableTailCallOpts()
[llvm-complete.git] / lib / CodeGen / CodeGenPrepare.cpp
blob486290d09a486ae34af66718fd3d2ffe3f415f30
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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/BlockFrequencyInfo.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Analysis/TargetTransformInfo.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/ISDOpcodes.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/TargetLowering.h"
38 #include "llvm/CodeGen/TargetPassConfig.h"
39 #include "llvm/CodeGen/TargetSubtargetInfo.h"
40 #include "llvm/CodeGen/ValueTypes.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/CallSite.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DerivedTypes.h"
50 #include "llvm/IR/Dominators.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/GlobalVariable.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"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/Intrinsics.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/MDBuilder.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/Operator.h"
66 #include "llvm/IR/PatternMatch.h"
67 #include "llvm/IR/Statepoint.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #include "llvm/IR/ValueMap.h"
74 #include "llvm/Pass.h"
75 #include "llvm/Support/BlockFrequency.h"
76 #include "llvm/Support/BranchProbability.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/MachineValueType.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetMachine.h"
86 #include "llvm/Target/TargetOptions.h"
87 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
88 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
89 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <limits>
95 #include <memory>
96 #include <utility>
97 #include <vector>
99 using namespace llvm;
100 using namespace llvm::PatternMatch;
102 #define DEBUG_TYPE "codegenprepare"
104 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
105 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
106 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
107 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
108 "sunken Cmps");
109 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
110 "of sunken Casts");
111 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
112 "computations were sunk");
113 STATISTIC(NumMemoryInstsPhiCreated,
114 "Number of phis created when address "
115 "computations were sunk to memory instructions");
116 STATISTIC(NumMemoryInstsSelectCreated,
117 "Number of select created when address "
118 "computations were sunk to memory instructions");
119 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
120 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
121 STATISTIC(NumAndsAdded,
122 "Number of and mask instructions added to form ext loads");
123 STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
124 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
125 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
126 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
127 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
129 static cl::opt<bool> DisableBranchOpts(
130 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
131 cl::desc("Disable branch optimizations in CodeGenPrepare"));
133 static cl::opt<bool>
134 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
135 cl::desc("Disable GC optimizations in CodeGenPrepare"));
137 static cl::opt<bool> DisableSelectToBranch(
138 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
139 cl::desc("Disable select to branch conversion."));
141 static cl::opt<bool> AddrSinkUsingGEPs(
142 "addr-sink-using-gep", cl::Hidden, cl::init(true),
143 cl::desc("Address sinking in CGP using GEPs."));
145 static cl::opt<bool> EnableAndCmpSinking(
146 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
147 cl::desc("Enable sinkinig and/cmp into branches."));
149 static cl::opt<bool> DisableStoreExtract(
150 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
151 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
153 static cl::opt<bool> StressStoreExtract(
154 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
155 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
157 static cl::opt<bool> DisableExtLdPromotion(
158 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
159 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
160 "CodeGenPrepare"));
162 static cl::opt<bool> StressExtLdPromotion(
163 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
164 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
165 "optimization in CodeGenPrepare"));
167 static cl::opt<bool> DisablePreheaderProtect(
168 "disable-preheader-prot", cl::Hidden, cl::init(false),
169 cl::desc("Disable protection against removing loop preheaders"));
171 static cl::opt<bool> ProfileGuidedSectionPrefix(
172 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
173 cl::desc("Use profile info to add section prefix for hot/cold functions"));
175 static cl::opt<unsigned> FreqRatioToSkipMerge(
176 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
177 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
178 "(frequency of destination block) is greater than this ratio"));
180 static cl::opt<bool> ForceSplitStore(
181 "force-split-store", cl::Hidden, cl::init(false),
182 cl::desc("Force store splitting no matter what the target query says."));
184 static cl::opt<bool>
185 EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
186 cl::desc("Enable merging of redundant sexts when one is dominating"
187 " the other."), cl::init(true));
189 static cl::opt<bool> DisableComplexAddrModes(
190 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
191 cl::desc("Disables combining addressing modes with different parts "
192 "in optimizeMemoryInst."));
194 static cl::opt<bool>
195 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
196 cl::desc("Allow creation of Phis in Address sinking."));
198 static cl::opt<bool>
199 AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
200 cl::desc("Allow creation of selects in Address sinking."));
202 static cl::opt<bool> AddrSinkCombineBaseReg(
203 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
204 cl::desc("Allow combining of BaseReg field in Address sinking."));
206 static cl::opt<bool> AddrSinkCombineBaseGV(
207 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
208 cl::desc("Allow combining of BaseGV field in Address sinking."));
210 static cl::opt<bool> AddrSinkCombineBaseOffs(
211 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
212 cl::desc("Allow combining of BaseOffs field in Address sinking."));
214 static cl::opt<bool> AddrSinkCombineScaledReg(
215 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
216 cl::desc("Allow combining of ScaledReg field in Address sinking."));
218 static cl::opt<bool>
219 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
220 cl::init(true),
221 cl::desc("Enable splitting large offset of GEP."));
223 namespace {
225 enum ExtType {
226 ZeroExtension, // Zero extension has been seen.
227 SignExtension, // Sign extension has been seen.
228 BothExtension // This extension type is used if we saw sext after
229 // ZeroExtension had been set, or if we saw zext after
230 // SignExtension had been set. It makes the type
231 // information of a promoted instruction invalid.
234 using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
235 using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
236 using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
237 using SExts = SmallVector<Instruction *, 16>;
238 using ValueToSExts = DenseMap<Value *, SExts>;
240 class TypePromotionTransaction;
242 class CodeGenPrepare : public FunctionPass {
243 const TargetMachine *TM = nullptr;
244 const TargetSubtargetInfo *SubtargetInfo;
245 const TargetLowering *TLI = nullptr;
246 const TargetRegisterInfo *TRI;
247 const TargetTransformInfo *TTI = nullptr;
248 const TargetLibraryInfo *TLInfo;
249 const LoopInfo *LI;
250 std::unique_ptr<BlockFrequencyInfo> BFI;
251 std::unique_ptr<BranchProbabilityInfo> BPI;
253 /// As we scan instructions optimizing them, this is the next instruction
254 /// to optimize. Transforms that can invalidate this should update it.
255 BasicBlock::iterator CurInstIterator;
257 /// Keeps track of non-local addresses that have been sunk into a block.
258 /// This allows us to avoid inserting duplicate code for blocks with
259 /// multiple load/stores of the same address. The usage of WeakTrackingVH
260 /// enables SunkAddrs to be treated as a cache whose entries can be
261 /// invalidated if a sunken address computation has been erased.
262 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
264 /// Keeps track of all instructions inserted for the current function.
265 SetOfInstrs InsertedInsts;
267 /// Keeps track of the type of the related instruction before their
268 /// promotion for the current function.
269 InstrToOrigTy PromotedInsts;
271 /// Keep track of instructions removed during promotion.
272 SetOfInstrs RemovedInsts;
274 /// Keep track of sext chains based on their initial value.
275 DenseMap<Value *, Instruction *> SeenChainsForSExt;
277 /// Keep track of GEPs accessing the same data structures such as structs or
278 /// arrays that are candidates to be split later because of their large
279 /// size.
280 MapVector<
281 AssertingVH<Value>,
282 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
283 LargeOffsetGEPMap;
285 /// Keep track of new GEP base after splitting the GEPs having large offset.
286 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
288 /// Map serial numbers to Large offset GEPs.
289 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
291 /// Keep track of SExt promoted.
292 ValueToSExts ValToSExtendedUses;
294 /// True if CFG is modified in any way.
295 bool ModifiedDT;
297 /// True if optimizing for size.
298 bool OptSize;
300 /// DataLayout for the Function being processed.
301 const DataLayout *DL = nullptr;
303 public:
304 static char ID; // Pass identification, replacement for typeid
306 CodeGenPrepare() : FunctionPass(ID) {
307 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
310 bool runOnFunction(Function &F) override;
312 StringRef getPassName() const override { return "CodeGen Prepare"; }
314 void getAnalysisUsage(AnalysisUsage &AU) const override {
315 // FIXME: When we can selectively preserve passes, preserve the domtree.
316 AU.addRequired<ProfileSummaryInfoWrapperPass>();
317 AU.addRequired<TargetLibraryInfoWrapperPass>();
318 AU.addRequired<TargetTransformInfoWrapperPass>();
319 AU.addRequired<LoopInfoWrapperPass>();
322 private:
323 template <typename F>
324 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
325 // Substituting can cause recursive simplifications, which can invalidate
326 // our iterator. Use a WeakTrackingVH to hold onto it in case this
327 // happens.
328 Value *CurValue = &*CurInstIterator;
329 WeakTrackingVH IterHandle(CurValue);
331 f();
333 // If the iterator instruction was recursively deleted, start over at the
334 // start of the block.
335 if (IterHandle != CurValue) {
336 CurInstIterator = BB->begin();
337 SunkAddrs.clear();
341 bool eliminateFallThrough(Function &F);
342 bool eliminateMostlyEmptyBlocks(Function &F);
343 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
344 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
345 void eliminateMostlyEmptyBlock(BasicBlock *BB);
346 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
347 bool isPreheader);
348 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
349 bool optimizeInst(Instruction *I, bool &ModifiedDT);
350 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
351 Type *AccessTy, unsigned AddrSpace);
352 bool optimizeInlineAsmInst(CallInst *CS);
353 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
354 bool optimizeExt(Instruction *&I);
355 bool optimizeExtUses(Instruction *I);
356 bool optimizeLoadExt(LoadInst *Load);
357 bool optimizeSelectInst(SelectInst *SI);
358 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
359 bool optimizeSwitchInst(SwitchInst *SI);
360 bool optimizeExtractElementInst(Instruction *Inst);
361 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
362 bool placeDbgValues(Function &F);
363 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
364 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
365 bool tryToPromoteExts(TypePromotionTransaction &TPT,
366 const SmallVectorImpl<Instruction *> &Exts,
367 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
368 unsigned CreatedInstsCost = 0);
369 bool mergeSExts(Function &F);
370 bool splitLargeGEPOffsets();
371 bool performAddressTypePromotion(
372 Instruction *&Inst,
373 bool AllowPromotionWithoutCommonHeader,
374 bool HasPromoted, TypePromotionTransaction &TPT,
375 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
376 bool splitBranchCondition(Function &F);
377 bool simplifyOffsetableRelocate(Instruction &I);
380 } // end anonymous namespace
382 char CodeGenPrepare::ID = 0;
384 INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
385 "Optimize for code generation", false, false)
386 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
387 INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
388 "Optimize for code generation", false, false)
390 FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
392 bool CodeGenPrepare::runOnFunction(Function &F) {
393 if (skipFunction(F))
394 return false;
396 DL = &F.getParent()->getDataLayout();
398 bool EverMadeChange = false;
399 // Clear per function information.
400 InsertedInsts.clear();
401 PromotedInsts.clear();
403 ModifiedDT = false;
404 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
405 TM = &TPC->getTM<TargetMachine>();
406 SubtargetInfo = TM->getSubtargetImpl(F);
407 TLI = SubtargetInfo->getTargetLowering();
408 TRI = SubtargetInfo->getRegisterInfo();
410 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
411 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
412 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
413 BPI.reset(new BranchProbabilityInfo(F, *LI));
414 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
415 OptSize = F.optForSize();
417 ProfileSummaryInfo *PSI =
418 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
419 if (ProfileGuidedSectionPrefix) {
420 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
421 F.setSectionPrefix(".hot");
422 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
423 F.setSectionPrefix(".unlikely");
426 /// This optimization identifies DIV instructions that can be
427 /// profitably bypassed and carried out with a shorter, faster divide.
428 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
429 TLI->isSlowDivBypassed()) {
430 const DenseMap<unsigned int, unsigned int> &BypassWidths =
431 TLI->getBypassSlowDivWidths();
432 BasicBlock* BB = &*F.begin();
433 while (BB != nullptr) {
434 // bypassSlowDivision may create new BBs, but we don't want to reapply the
435 // optimization to those blocks.
436 BasicBlock* Next = BB->getNextNode();
437 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
438 BB = Next;
442 // Eliminate blocks that contain only PHI nodes and an
443 // unconditional branch.
444 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
446 if (!DisableBranchOpts)
447 EverMadeChange |= splitBranchCondition(F);
449 // Split some critical edges where one of the sources is an indirect branch,
450 // to help generate sane code for PHIs involving such edges.
451 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
453 bool MadeChange = true;
454 while (MadeChange) {
455 MadeChange = false;
456 for (Function::iterator I = F.begin(); I != F.end(); ) {
457 BasicBlock *BB = &*I++;
458 bool ModifiedDTOnIteration = false;
459 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
461 // Restart BB iteration if the dominator tree of the Function was changed
462 if (ModifiedDTOnIteration)
463 break;
465 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
466 MadeChange |= mergeSExts(F);
467 if (!LargeOffsetGEPMap.empty())
468 MadeChange |= splitLargeGEPOffsets();
470 // Really free removed instructions during promotion.
471 for (Instruction *I : RemovedInsts)
472 I->deleteValue();
474 EverMadeChange |= MadeChange;
475 SeenChainsForSExt.clear();
476 ValToSExtendedUses.clear();
477 RemovedInsts.clear();
478 LargeOffsetGEPMap.clear();
479 LargeOffsetGEPID.clear();
482 SunkAddrs.clear();
484 if (!DisableBranchOpts) {
485 MadeChange = false;
486 // Use a set vector to get deterministic iteration order. The order the
487 // blocks are removed may affect whether or not PHI nodes in successors
488 // are removed.
489 SmallSetVector<BasicBlock*, 8> WorkList;
490 for (BasicBlock &BB : F) {
491 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
492 MadeChange |= ConstantFoldTerminator(&BB, true);
493 if (!MadeChange) continue;
495 for (SmallVectorImpl<BasicBlock*>::iterator
496 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
497 if (pred_begin(*II) == pred_end(*II))
498 WorkList.insert(*II);
501 // Delete the dead blocks and any of their dead successors.
502 MadeChange |= !WorkList.empty();
503 while (!WorkList.empty()) {
504 BasicBlock *BB = WorkList.pop_back_val();
505 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
507 DeleteDeadBlock(BB);
509 for (SmallVectorImpl<BasicBlock*>::iterator
510 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
511 if (pred_begin(*II) == pred_end(*II))
512 WorkList.insert(*II);
515 // Merge pairs of basic blocks with unconditional branches, connected by
516 // a single edge.
517 if (EverMadeChange || MadeChange)
518 MadeChange |= eliminateFallThrough(F);
520 EverMadeChange |= MadeChange;
523 if (!DisableGCOpts) {
524 SmallVector<Instruction *, 2> Statepoints;
525 for (BasicBlock &BB : F)
526 for (Instruction &I : BB)
527 if (isStatepoint(I))
528 Statepoints.push_back(&I);
529 for (auto &I : Statepoints)
530 EverMadeChange |= simplifyOffsetableRelocate(*I);
533 // Do this last to clean up use-before-def scenarios introduced by other
534 // preparatory transforms.
535 EverMadeChange |= placeDbgValues(F);
537 return EverMadeChange;
540 /// Merge basic blocks which are connected by a single edge, where one of the
541 /// basic blocks has a single successor pointing to the other basic block,
542 /// which has a single predecessor.
543 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
544 bool Changed = false;
545 // Scan all of the blocks in the function, except for the entry block.
546 // Use a temporary array to avoid iterator being invalidated when
547 // deleting blocks.
548 SmallVector<WeakTrackingVH, 16> Blocks;
549 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
550 Blocks.push_back(&Block);
552 for (auto &Block : Blocks) {
553 auto *BB = cast_or_null<BasicBlock>(Block);
554 if (!BB)
555 continue;
556 // If the destination block has a single pred, then this is a trivial
557 // edge, just collapse it.
558 BasicBlock *SinglePred = BB->getSinglePredecessor();
560 // Don't merge if BB's address is taken.
561 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
563 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
564 if (Term && !Term->isConditional()) {
565 Changed = true;
566 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
568 // Merge BB into SinglePred and delete it.
569 MergeBlockIntoPredecessor(BB);
572 return Changed;
575 /// Find a destination block from BB if BB is mergeable empty block.
576 BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
577 // If this block doesn't end with an uncond branch, ignore it.
578 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
579 if (!BI || !BI->isUnconditional())
580 return nullptr;
582 // If the instruction before the branch (skipping debug info) isn't a phi
583 // node, then other stuff is happening here.
584 BasicBlock::iterator BBI = BI->getIterator();
585 if (BBI != BB->begin()) {
586 --BBI;
587 while (isa<DbgInfoIntrinsic>(BBI)) {
588 if (BBI == BB->begin())
589 break;
590 --BBI;
592 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
593 return nullptr;
596 // Do not break infinite loops.
597 BasicBlock *DestBB = BI->getSuccessor(0);
598 if (DestBB == BB)
599 return nullptr;
601 if (!canMergeBlocks(BB, DestBB))
602 DestBB = nullptr;
604 return DestBB;
607 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
608 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
609 /// edges in ways that are non-optimal for isel. Start by eliminating these
610 /// blocks so we can split them the way we want them.
611 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
612 SmallPtrSet<BasicBlock *, 16> Preheaders;
613 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
614 while (!LoopList.empty()) {
615 Loop *L = LoopList.pop_back_val();
616 LoopList.insert(LoopList.end(), L->begin(), L->end());
617 if (BasicBlock *Preheader = L->getLoopPreheader())
618 Preheaders.insert(Preheader);
621 bool MadeChange = false;
622 // Copy blocks into a temporary array to avoid iterator invalidation issues
623 // as we remove them.
624 // Note that this intentionally skips the entry block.
625 SmallVector<WeakTrackingVH, 16> Blocks;
626 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
627 Blocks.push_back(&Block);
629 for (auto &Block : Blocks) {
630 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
631 if (!BB)
632 continue;
633 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
634 if (!DestBB ||
635 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
636 continue;
638 eliminateMostlyEmptyBlock(BB);
639 MadeChange = true;
641 return MadeChange;
644 bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
645 BasicBlock *DestBB,
646 bool isPreheader) {
647 // Do not delete loop preheaders if doing so would create a critical edge.
648 // Loop preheaders can be good locations to spill registers. If the
649 // preheader is deleted and we create a critical edge, registers may be
650 // spilled in the loop body instead.
651 if (!DisablePreheaderProtect && isPreheader &&
652 !(BB->getSinglePredecessor() &&
653 BB->getSinglePredecessor()->getSingleSuccessor()))
654 return false;
656 // Try to skip merging if the unique predecessor of BB is terminated by a
657 // switch or indirect branch instruction, and BB is used as an incoming block
658 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
659 // add COPY instructions in the predecessor of BB instead of BB (if it is not
660 // merged). Note that the critical edge created by merging such blocks wont be
661 // split in MachineSink because the jump table is not analyzable. By keeping
662 // such empty block (BB), ISel will place COPY instructions in BB, not in the
663 // predecessor of BB.
664 BasicBlock *Pred = BB->getUniquePredecessor();
665 if (!Pred ||
666 !(isa<SwitchInst>(Pred->getTerminator()) ||
667 isa<IndirectBrInst>(Pred->getTerminator())))
668 return true;
670 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
671 return true;
673 // We use a simple cost heuristic which determine skipping merging is
674 // profitable if the cost of skipping merging is less than the cost of
675 // merging : Cost(skipping merging) < Cost(merging BB), where the
676 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
677 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
678 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
679 // Freq(Pred) / Freq(BB) > 2.
680 // Note that if there are multiple empty blocks sharing the same incoming
681 // value for the PHIs in the DestBB, we consider them together. In such
682 // case, Cost(merging BB) will be the sum of their frequencies.
684 if (!isa<PHINode>(DestBB->begin()))
685 return true;
687 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
689 // Find all other incoming blocks from which incoming values of all PHIs in
690 // DestBB are the same as the ones from BB.
691 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
692 ++PI) {
693 BasicBlock *DestBBPred = *PI;
694 if (DestBBPred == BB)
695 continue;
697 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
698 return DestPN.getIncomingValueForBlock(BB) ==
699 DestPN.getIncomingValueForBlock(DestBBPred);
701 SameIncomingValueBBs.insert(DestBBPred);
704 // See if all BB's incoming values are same as the value from Pred. In this
705 // case, no reason to skip merging because COPYs are expected to be place in
706 // Pred already.
707 if (SameIncomingValueBBs.count(Pred))
708 return true;
710 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
711 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
713 for (auto SameValueBB : SameIncomingValueBBs)
714 if (SameValueBB->getUniquePredecessor() == Pred &&
715 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
716 BBFreq += BFI->getBlockFreq(SameValueBB);
718 return PredFreq.getFrequency() <=
719 BBFreq.getFrequency() * FreqRatioToSkipMerge;
722 /// Return true if we can merge BB into DestBB if there is a single
723 /// unconditional branch between them, and BB contains no other non-phi
724 /// instructions.
725 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
726 const BasicBlock *DestBB) const {
727 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
728 // the successor. If there are more complex condition (e.g. preheaders),
729 // don't mess around with them.
730 for (const PHINode &PN : BB->phis()) {
731 for (const User *U : PN.users()) {
732 const Instruction *UI = cast<Instruction>(U);
733 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
734 return false;
735 // If User is inside DestBB block and it is a PHINode then check
736 // incoming value. If incoming value is not from BB then this is
737 // a complex condition (e.g. preheaders) we want to avoid here.
738 if (UI->getParent() == DestBB) {
739 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
740 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
741 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
742 if (Insn && Insn->getParent() == BB &&
743 Insn->getParent() != UPN->getIncomingBlock(I))
744 return false;
750 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
751 // and DestBB may have conflicting incoming values for the block. If so, we
752 // can't merge the block.
753 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
754 if (!DestBBPN) return true; // no conflict.
756 // Collect the preds of BB.
757 SmallPtrSet<const BasicBlock*, 16> BBPreds;
758 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
759 // It is faster to get preds from a PHI than with pred_iterator.
760 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
761 BBPreds.insert(BBPN->getIncomingBlock(i));
762 } else {
763 BBPreds.insert(pred_begin(BB), pred_end(BB));
766 // Walk the preds of DestBB.
767 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
768 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
769 if (BBPreds.count(Pred)) { // Common predecessor?
770 for (const PHINode &PN : DestBB->phis()) {
771 const Value *V1 = PN.getIncomingValueForBlock(Pred);
772 const Value *V2 = PN.getIncomingValueForBlock(BB);
774 // If V2 is a phi node in BB, look up what the mapped value will be.
775 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
776 if (V2PN->getParent() == BB)
777 V2 = V2PN->getIncomingValueForBlock(Pred);
779 // If there is a conflict, bail out.
780 if (V1 != V2) return false;
785 return true;
788 /// Eliminate a basic block that has only phi's and an unconditional branch in
789 /// it.
790 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
791 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
792 BasicBlock *DestBB = BI->getSuccessor(0);
794 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
795 << *BB << *DestBB);
797 // If the destination block has a single pred, then this is a trivial edge,
798 // just collapse it.
799 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
800 if (SinglePred != DestBB) {
801 assert(SinglePred == BB &&
802 "Single predecessor not the same as predecessor");
803 // Merge DestBB into SinglePred/BB and delete it.
804 MergeBlockIntoPredecessor(DestBB);
805 // Note: BB(=SinglePred) will not be deleted on this path.
806 // DestBB(=its single successor) is the one that was deleted.
807 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
808 return;
812 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
813 // to handle the new incoming edges it is about to have.
814 for (PHINode &PN : DestBB->phis()) {
815 // Remove the incoming value for BB, and remember it.
816 Value *InVal = PN.removeIncomingValue(BB, false);
818 // Two options: either the InVal is a phi node defined in BB or it is some
819 // value that dominates BB.
820 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
821 if (InValPhi && InValPhi->getParent() == BB) {
822 // Add all of the input values of the input PHI as inputs of this phi.
823 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
824 PN.addIncoming(InValPhi->getIncomingValue(i),
825 InValPhi->getIncomingBlock(i));
826 } else {
827 // Otherwise, add one instance of the dominating value for each edge that
828 // we will be adding.
829 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
830 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
831 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
832 } else {
833 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
834 PN.addIncoming(InVal, *PI);
839 // The PHIs are now updated, change everything that refers to BB to use
840 // DestBB and remove BB.
841 BB->replaceAllUsesWith(DestBB);
842 BB->eraseFromParent();
843 ++NumBlocksElim;
845 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
848 // Computes a map of base pointer relocation instructions to corresponding
849 // derived pointer relocation instructions given a vector of all relocate calls
850 static void computeBaseDerivedRelocateMap(
851 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
852 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
853 &RelocateInstMap) {
854 // Collect information in two maps: one primarily for locating the base object
855 // while filling the second map; the second map is the final structure holding
856 // a mapping between Base and corresponding Derived relocate calls
857 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
858 for (auto *ThisRelocate : AllRelocateCalls) {
859 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
860 ThisRelocate->getDerivedPtrIndex());
861 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
863 for (auto &Item : RelocateIdxMap) {
864 std::pair<unsigned, unsigned> Key = Item.first;
865 if (Key.first == Key.second)
866 // Base relocation: nothing to insert
867 continue;
869 GCRelocateInst *I = Item.second;
870 auto BaseKey = std::make_pair(Key.first, Key.first);
872 // We're iterating over RelocateIdxMap so we cannot modify it.
873 auto MaybeBase = RelocateIdxMap.find(BaseKey);
874 if (MaybeBase == RelocateIdxMap.end())
875 // TODO: We might want to insert a new base object relocate and gep off
876 // that, if there are enough derived object relocates.
877 continue;
879 RelocateInstMap[MaybeBase->second].push_back(I);
883 // Accepts a GEP and extracts the operands into a vector provided they're all
884 // small integer constants
885 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
886 SmallVectorImpl<Value *> &OffsetV) {
887 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
888 // Only accept small constant integer operands
889 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
890 if (!Op || Op->getZExtValue() > 20)
891 return false;
894 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
895 OffsetV.push_back(GEP->getOperand(i));
896 return true;
899 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
900 // replace, computes a replacement, and affects it.
901 static bool
902 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
903 const SmallVectorImpl<GCRelocateInst *> &Targets) {
904 bool MadeChange = false;
905 // We must ensure the relocation of derived pointer is defined after
906 // relocation of base pointer. If we find a relocation corresponding to base
907 // defined earlier than relocation of base then we move relocation of base
908 // right before found relocation. We consider only relocation in the same
909 // basic block as relocation of base. Relocations from other basic block will
910 // be skipped by optimization and we do not care about them.
911 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
912 &*R != RelocatedBase; ++R)
913 if (auto RI = dyn_cast<GCRelocateInst>(R))
914 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
915 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
916 RelocatedBase->moveBefore(RI);
917 break;
920 for (GCRelocateInst *ToReplace : Targets) {
921 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
922 "Not relocating a derived object of the original base object");
923 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
924 // A duplicate relocate call. TODO: coalesce duplicates.
925 continue;
928 if (RelocatedBase->getParent() != ToReplace->getParent()) {
929 // Base and derived relocates are in different basic blocks.
930 // In this case transform is only valid when base dominates derived
931 // relocate. However it would be too expensive to check dominance
932 // for each such relocate, so we skip the whole transformation.
933 continue;
936 Value *Base = ToReplace->getBasePtr();
937 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
938 if (!Derived || Derived->getPointerOperand() != Base)
939 continue;
941 SmallVector<Value *, 2> OffsetV;
942 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
943 continue;
945 // Create a Builder and replace the target callsite with a gep
946 assert(RelocatedBase->getNextNode() &&
947 "Should always have one since it's not a terminator");
949 // Insert after RelocatedBase
950 IRBuilder<> Builder(RelocatedBase->getNextNode());
951 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
953 // If gc_relocate does not match the actual type, cast it to the right type.
954 // In theory, there must be a bitcast after gc_relocate if the type does not
955 // match, and we should reuse it to get the derived pointer. But it could be
956 // cases like this:
957 // bb1:
958 // ...
959 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
960 // br label %merge
962 // bb2:
963 // ...
964 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
965 // br label %merge
967 // merge:
968 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
969 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
971 // In this case, we can not find the bitcast any more. So we insert a new bitcast
972 // no matter there is already one or not. In this way, we can handle all cases, and
973 // the extra bitcast should be optimized away in later passes.
974 Value *ActualRelocatedBase = RelocatedBase;
975 if (RelocatedBase->getType() != Base->getType()) {
976 ActualRelocatedBase =
977 Builder.CreateBitCast(RelocatedBase, Base->getType());
979 Value *Replacement = Builder.CreateGEP(
980 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
981 Replacement->takeName(ToReplace);
982 // If the newly generated derived pointer's type does not match the original derived
983 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
984 Value *ActualReplacement = Replacement;
985 if (Replacement->getType() != ToReplace->getType()) {
986 ActualReplacement =
987 Builder.CreateBitCast(Replacement, ToReplace->getType());
989 ToReplace->replaceAllUsesWith(ActualReplacement);
990 ToReplace->eraseFromParent();
992 MadeChange = true;
994 return MadeChange;
997 // Turns this:
999 // %base = ...
1000 // %ptr = gep %base + 15
1001 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1002 // %base' = relocate(%tok, i32 4, i32 4)
1003 // %ptr' = relocate(%tok, i32 4, i32 5)
1004 // %val = load %ptr'
1006 // into this:
1008 // %base = ...
1009 // %ptr = gep %base + 15
1010 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1011 // %base' = gc.relocate(%tok, i32 4, i32 4)
1012 // %ptr' = gep %base' + 15
1013 // %val = load %ptr'
1014 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1015 bool MadeChange = false;
1016 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1018 for (auto *U : I.users())
1019 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1020 // Collect all the relocate calls associated with a statepoint
1021 AllRelocateCalls.push_back(Relocate);
1023 // We need atleast one base pointer relocation + one derived pointer
1024 // relocation to mangle
1025 if (AllRelocateCalls.size() < 2)
1026 return false;
1028 // RelocateInstMap is a mapping from the base relocate instruction to the
1029 // corresponding derived relocate instructions
1030 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1031 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1032 if (RelocateInstMap.empty())
1033 return false;
1035 for (auto &Item : RelocateInstMap)
1036 // Item.first is the RelocatedBase to offset against
1037 // Item.second is the vector of Targets to replace
1038 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1039 return MadeChange;
1042 /// SinkCast - Sink the specified cast instruction into its user blocks
1043 static bool SinkCast(CastInst *CI) {
1044 BasicBlock *DefBB = CI->getParent();
1046 /// InsertedCasts - Only insert a cast in each block once.
1047 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1049 bool MadeChange = false;
1050 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1051 UI != E; ) {
1052 Use &TheUse = UI.getUse();
1053 Instruction *User = cast<Instruction>(*UI);
1055 // Figure out which BB this cast is used in. For PHI's this is the
1056 // appropriate predecessor block.
1057 BasicBlock *UserBB = User->getParent();
1058 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1059 UserBB = PN->getIncomingBlock(TheUse);
1062 // Preincrement use iterator so we don't invalidate it.
1063 ++UI;
1065 // The first insertion point of a block containing an EH pad is after the
1066 // pad. If the pad is the user, we cannot sink the cast past the pad.
1067 if (User->isEHPad())
1068 continue;
1070 // If the block selected to receive the cast is an EH pad that does not
1071 // allow non-PHI instructions before the terminator, we can't sink the
1072 // cast.
1073 if (UserBB->getTerminator()->isEHPad())
1074 continue;
1076 // If this user is in the same block as the cast, don't change the cast.
1077 if (UserBB == DefBB) continue;
1079 // If we have already inserted a cast into this block, use it.
1080 CastInst *&InsertedCast = InsertedCasts[UserBB];
1082 if (!InsertedCast) {
1083 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1084 assert(InsertPt != UserBB->end());
1085 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1086 CI->getType(), "", &*InsertPt);
1087 InsertedCast->setDebugLoc(CI->getDebugLoc());
1090 // Replace a use of the cast with a use of the new cast.
1091 TheUse = InsertedCast;
1092 MadeChange = true;
1093 ++NumCastUses;
1096 // If we removed all uses, nuke the cast.
1097 if (CI->use_empty()) {
1098 salvageDebugInfo(*CI);
1099 CI->eraseFromParent();
1100 MadeChange = true;
1103 return MadeChange;
1106 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1107 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1108 /// reduce the number of virtual registers that must be created and coalesced.
1110 /// Return true if any changes are made.
1111 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1112 const DataLayout &DL) {
1113 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1114 // than sinking only nop casts, but is helpful on some platforms.
1115 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1116 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1117 ASC->getDestAddressSpace()))
1118 return false;
1121 // If this is a noop copy,
1122 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1123 EVT DstVT = TLI.getValueType(DL, CI->getType());
1125 // This is an fp<->int conversion?
1126 if (SrcVT.isInteger() != DstVT.isInteger())
1127 return false;
1129 // If this is an extension, it will be a zero or sign extension, which
1130 // isn't a noop.
1131 if (SrcVT.bitsLT(DstVT)) return false;
1133 // If these values will be promoted, find out what they will be promoted
1134 // to. This helps us consider truncates on PPC as noop copies when they
1135 // are.
1136 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1137 TargetLowering::TypePromoteInteger)
1138 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1139 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1140 TargetLowering::TypePromoteInteger)
1141 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1143 // If, after promotion, these are the same types, this is a noop copy.
1144 if (SrcVT != DstVT)
1145 return false;
1147 return SinkCast(CI);
1150 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1151 /// possible.
1153 /// Return true if any changes were made.
1154 static bool CombineUAddWithOverflow(CmpInst *CI) {
1155 Value *A, *B;
1156 Instruction *AddI;
1157 if (!match(CI,
1158 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1159 return false;
1161 Type *Ty = AddI->getType();
1162 if (!isa<IntegerType>(Ty))
1163 return false;
1165 // We don't want to move around uses of condition values this late, so we we
1166 // check if it is legal to create the call to the intrinsic in the basic
1167 // block containing the icmp:
1169 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1170 return false;
1172 #ifndef NDEBUG
1173 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1174 // for now:
1175 if (AddI->hasOneUse())
1176 assert(*AddI->user_begin() == CI && "expected!");
1177 #endif
1179 Module *M = CI->getModule();
1180 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1182 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1184 DebugLoc Loc = CI->getDebugLoc();
1185 auto *UAddWithOverflow =
1186 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1187 UAddWithOverflow->setDebugLoc(Loc);
1188 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1189 UAdd->setDebugLoc(Loc);
1190 auto *Overflow =
1191 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1192 Overflow->setDebugLoc(Loc);
1194 CI->replaceAllUsesWith(Overflow);
1195 AddI->replaceAllUsesWith(UAdd);
1196 CI->eraseFromParent();
1197 AddI->eraseFromParent();
1198 return true;
1201 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1202 /// registers that must be created and coalesced. This is a clear win except on
1203 /// targets with multiple condition code registers (PowerPC), where it might
1204 /// lose; some adjustment may be wanted there.
1206 /// Return true if any changes are made.
1207 static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
1208 BasicBlock *DefBB = CI->getParent();
1210 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1211 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
1212 return false;
1214 // Only insert a cmp in each block once.
1215 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1217 bool MadeChange = false;
1218 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1219 UI != E; ) {
1220 Use &TheUse = UI.getUse();
1221 Instruction *User = cast<Instruction>(*UI);
1223 // Preincrement use iterator so we don't invalidate it.
1224 ++UI;
1226 // Don't bother for PHI nodes.
1227 if (isa<PHINode>(User))
1228 continue;
1230 // Figure out which BB this cmp is used in.
1231 BasicBlock *UserBB = User->getParent();
1233 // If this user is in the same block as the cmp, don't change the cmp.
1234 if (UserBB == DefBB) continue;
1236 // If we have already inserted a cmp into this block, use it.
1237 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1239 if (!InsertedCmp) {
1240 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1241 assert(InsertPt != UserBB->end());
1242 InsertedCmp =
1243 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1244 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1245 // Propagate the debug info.
1246 InsertedCmp->setDebugLoc(CI->getDebugLoc());
1249 // Replace a use of the cmp with a use of the new cmp.
1250 TheUse = InsertedCmp;
1251 MadeChange = true;
1252 ++NumCmpUses;
1255 // If we removed all uses, nuke the cmp.
1256 if (CI->use_empty()) {
1257 CI->eraseFromParent();
1258 MadeChange = true;
1261 return MadeChange;
1264 static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
1265 if (SinkCmpExpression(CI, TLI))
1266 return true;
1268 if (CombineUAddWithOverflow(CI))
1269 return true;
1271 return false;
1274 /// Duplicate and sink the given 'and' instruction into user blocks where it is
1275 /// used in a compare to allow isel to generate better code for targets where
1276 /// this operation can be combined.
1278 /// Return true if any changes are made.
1279 static bool sinkAndCmp0Expression(Instruction *AndI,
1280 const TargetLowering &TLI,
1281 SetOfInstrs &InsertedInsts) {
1282 // Double-check that we're not trying to optimize an instruction that was
1283 // already optimized by some other part of this pass.
1284 assert(!InsertedInsts.count(AndI) &&
1285 "Attempting to optimize already optimized and instruction");
1286 (void) InsertedInsts;
1288 // Nothing to do for single use in same basic block.
1289 if (AndI->hasOneUse() &&
1290 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1291 return false;
1293 // Try to avoid cases where sinking/duplicating is likely to increase register
1294 // pressure.
1295 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1296 !isa<ConstantInt>(AndI->getOperand(1)) &&
1297 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1298 return false;
1300 for (auto *U : AndI->users()) {
1301 Instruction *User = cast<Instruction>(U);
1303 // Only sink for and mask feeding icmp with 0.
1304 if (!isa<ICmpInst>(User))
1305 return false;
1307 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1308 if (!CmpC || !CmpC->isZero())
1309 return false;
1312 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1313 return false;
1315 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1316 LLVM_DEBUG(AndI->getParent()->dump());
1318 // Push the 'and' into the same block as the icmp 0. There should only be
1319 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1320 // others, so we don't need to keep track of which BBs we insert into.
1321 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1322 UI != E; ) {
1323 Use &TheUse = UI.getUse();
1324 Instruction *User = cast<Instruction>(*UI);
1326 // Preincrement use iterator so we don't invalidate it.
1327 ++UI;
1329 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1331 // Keep the 'and' in the same place if the use is already in the same block.
1332 Instruction *InsertPt =
1333 User->getParent() == AndI->getParent() ? AndI : User;
1334 Instruction *InsertedAnd =
1335 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1336 AndI->getOperand(1), "", InsertPt);
1337 // Propagate the debug info.
1338 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1340 // Replace a use of the 'and' with a use of the new 'and'.
1341 TheUse = InsertedAnd;
1342 ++NumAndUses;
1343 LLVM_DEBUG(User->getParent()->dump());
1346 // We removed all uses, nuke the and.
1347 AndI->eraseFromParent();
1348 return true;
1351 /// Check if the candidates could be combined with a shift instruction, which
1352 /// includes:
1353 /// 1. Truncate instruction
1354 /// 2. And instruction and the imm is a mask of the low bits:
1355 /// imm & (imm+1) == 0
1356 static bool isExtractBitsCandidateUse(Instruction *User) {
1357 if (!isa<TruncInst>(User)) {
1358 if (User->getOpcode() != Instruction::And ||
1359 !isa<ConstantInt>(User->getOperand(1)))
1360 return false;
1362 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1364 if ((Cimm & (Cimm + 1)).getBoolValue())
1365 return false;
1367 return true;
1370 /// Sink both shift and truncate instruction to the use of truncate's BB.
1371 static bool
1372 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1373 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1374 const TargetLowering &TLI, const DataLayout &DL) {
1375 BasicBlock *UserBB = User->getParent();
1376 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1377 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1378 bool MadeChange = false;
1380 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1381 TruncE = TruncI->user_end();
1382 TruncUI != TruncE;) {
1384 Use &TruncTheUse = TruncUI.getUse();
1385 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1386 // Preincrement use iterator so we don't invalidate it.
1388 ++TruncUI;
1390 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1391 if (!ISDOpcode)
1392 continue;
1394 // If the use is actually a legal node, there will not be an
1395 // implicit truncate.
1396 // FIXME: always querying the result type is just an
1397 // approximation; some nodes' legality is determined by the
1398 // operand or other means. There's no good way to find out though.
1399 if (TLI.isOperationLegalOrCustom(
1400 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1401 continue;
1403 // Don't bother for PHI nodes.
1404 if (isa<PHINode>(TruncUser))
1405 continue;
1407 BasicBlock *TruncUserBB = TruncUser->getParent();
1409 if (UserBB == TruncUserBB)
1410 continue;
1412 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1413 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1415 if (!InsertedShift && !InsertedTrunc) {
1416 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1417 assert(InsertPt != TruncUserBB->end());
1418 // Sink the shift
1419 if (ShiftI->getOpcode() == Instruction::AShr)
1420 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1421 "", &*InsertPt);
1422 else
1423 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1424 "", &*InsertPt);
1425 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
1427 // Sink the trunc
1428 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1429 TruncInsertPt++;
1430 assert(TruncInsertPt != TruncUserBB->end());
1432 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
1433 TruncI->getType(), "", &*TruncInsertPt);
1434 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
1436 MadeChange = true;
1438 TruncTheUse = InsertedTrunc;
1441 return MadeChange;
1444 /// Sink the shift *right* instruction into user blocks if the uses could
1445 /// potentially be combined with this shift instruction and generate BitExtract
1446 /// instruction. It will only be applied if the architecture supports BitExtract
1447 /// instruction. Here is an example:
1448 /// BB1:
1449 /// %x.extract.shift = lshr i64 %arg1, 32
1450 /// BB2:
1451 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1452 /// ==>
1454 /// BB2:
1455 /// %x.extract.shift.1 = lshr i64 %arg1, 32
1456 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1458 /// CodeGen will recognize the pattern in BB2 and generate BitExtract
1459 /// instruction.
1460 /// Return true if any changes are made.
1461 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1462 const TargetLowering &TLI,
1463 const DataLayout &DL) {
1464 BasicBlock *DefBB = ShiftI->getParent();
1466 /// Only insert instructions in each block once.
1467 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1469 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1471 bool MadeChange = false;
1472 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1473 UI != E;) {
1474 Use &TheUse = UI.getUse();
1475 Instruction *User = cast<Instruction>(*UI);
1476 // Preincrement use iterator so we don't invalidate it.
1477 ++UI;
1479 // Don't bother for PHI nodes.
1480 if (isa<PHINode>(User))
1481 continue;
1483 if (!isExtractBitsCandidateUse(User))
1484 continue;
1486 BasicBlock *UserBB = User->getParent();
1488 if (UserBB == DefBB) {
1489 // If the shift and truncate instruction are in the same BB. The use of
1490 // the truncate(TruncUse) may still introduce another truncate if not
1491 // legal. In this case, we would like to sink both shift and truncate
1492 // instruction to the BB of TruncUse.
1493 // for example:
1494 // BB1:
1495 // i64 shift.result = lshr i64 opnd, imm
1496 // trunc.result = trunc shift.result to i16
1498 // BB2:
1499 // ----> We will have an implicit truncate here if the architecture does
1500 // not have i16 compare.
1501 // cmp i16 trunc.result, opnd2
1503 if (isa<TruncInst>(User) && shiftIsLegal
1504 // If the type of the truncate is legal, no truncate will be
1505 // introduced in other basic blocks.
1507 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1508 MadeChange =
1509 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1511 continue;
1513 // If we have already inserted a shift into this block, use it.
1514 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1516 if (!InsertedShift) {
1517 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1518 assert(InsertPt != UserBB->end());
1520 if (ShiftI->getOpcode() == Instruction::AShr)
1521 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1522 "", &*InsertPt);
1523 else
1524 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1525 "", &*InsertPt);
1526 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
1528 MadeChange = true;
1531 // Replace a use of the shift with a use of the new shift.
1532 TheUse = InsertedShift;
1535 // If we removed all uses, nuke the shift.
1536 if (ShiftI->use_empty()) {
1537 salvageDebugInfo(*ShiftI);
1538 ShiftI->eraseFromParent();
1541 return MadeChange;
1544 /// If counting leading or trailing zeros is an expensive operation and a zero
1545 /// input is defined, add a check for zero to avoid calling the intrinsic.
1547 /// We want to transform:
1548 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1550 /// into:
1551 /// entry:
1552 /// %cmpz = icmp eq i64 %A, 0
1553 /// br i1 %cmpz, label %cond.end, label %cond.false
1554 /// cond.false:
1555 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1556 /// br label %cond.end
1557 /// cond.end:
1558 /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1560 /// If the transform is performed, return true and set ModifiedDT to true.
1561 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1562 const TargetLowering *TLI,
1563 const DataLayout *DL,
1564 bool &ModifiedDT) {
1565 if (!TLI || !DL)
1566 return false;
1568 // If a zero input is undefined, it doesn't make sense to despeculate that.
1569 if (match(CountZeros->getOperand(1), m_One()))
1570 return false;
1572 // If it's cheap to speculate, there's nothing to do.
1573 auto IntrinsicID = CountZeros->getIntrinsicID();
1574 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1575 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1576 return false;
1578 // Only handle legal scalar cases. Anything else requires too much work.
1579 Type *Ty = CountZeros->getType();
1580 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1581 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
1582 return false;
1584 // The intrinsic will be sunk behind a compare against zero and branch.
1585 BasicBlock *StartBlock = CountZeros->getParent();
1586 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1588 // Create another block after the count zero intrinsic. A PHI will be added
1589 // in this block to select the result of the intrinsic or the bit-width
1590 // constant if the input to the intrinsic is zero.
1591 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1592 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1594 // Set up a builder to create a compare, conditional branch, and PHI.
1595 IRBuilder<> Builder(CountZeros->getContext());
1596 Builder.SetInsertPoint(StartBlock->getTerminator());
1597 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1599 // Replace the unconditional branch that was created by the first split with
1600 // a compare against zero and a conditional branch.
1601 Value *Zero = Constant::getNullValue(Ty);
1602 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1603 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1604 StartBlock->getTerminator()->eraseFromParent();
1606 // Create a PHI in the end block to select either the output of the intrinsic
1607 // or the bit width of the operand.
1608 Builder.SetInsertPoint(&EndBlock->front());
1609 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1610 CountZeros->replaceAllUsesWith(PN);
1611 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1612 PN->addIncoming(BitWidth, StartBlock);
1613 PN->addIncoming(CountZeros, CallBlock);
1615 // We are explicitly handling the zero case, so we can set the intrinsic's
1616 // undefined zero argument to 'true'. This will also prevent reprocessing the
1617 // intrinsic; we only despeculate when a zero input is defined.
1618 CountZeros->setArgOperand(1, Builder.getTrue());
1619 ModifiedDT = true;
1620 return true;
1623 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
1624 BasicBlock *BB = CI->getParent();
1626 // Lower inline assembly if we can.
1627 // If we found an inline asm expession, and if the target knows how to
1628 // lower it to normal LLVM code, do so now.
1629 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1630 if (TLI->ExpandInlineAsm(CI)) {
1631 // Avoid invalidating the iterator.
1632 CurInstIterator = BB->begin();
1633 // Avoid processing instructions out of order, which could cause
1634 // reuse before a value is defined.
1635 SunkAddrs.clear();
1636 return true;
1638 // Sink address computing for memory operands into the block.
1639 if (optimizeInlineAsmInst(CI))
1640 return true;
1643 // Align the pointer arguments to this call if the target thinks it's a good
1644 // idea
1645 unsigned MinSize, PrefAlign;
1646 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1647 for (auto &Arg : CI->arg_operands()) {
1648 // We want to align both objects whose address is used directly and
1649 // objects whose address is used in casts and GEPs, though it only makes
1650 // sense for GEPs if the offset is a multiple of the desired alignment and
1651 // if size - offset meets the size threshold.
1652 if (!Arg->getType()->isPointerTy())
1653 continue;
1654 APInt Offset(DL->getIndexSizeInBits(
1655 cast<PointerType>(Arg->getType())->getAddressSpace()),
1657 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
1658 uint64_t Offset2 = Offset.getLimitedValue();
1659 if ((Offset2 & (PrefAlign-1)) != 0)
1660 continue;
1661 AllocaInst *AI;
1662 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1663 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
1664 AI->setAlignment(PrefAlign);
1665 // Global variables can only be aligned if they are defined in this
1666 // object (i.e. they are uniquely initialized in this object), and
1667 // over-aligning global variables that have an explicit section is
1668 // forbidden.
1669 GlobalVariable *GV;
1670 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
1671 GV->getPointerAlignment(*DL) < PrefAlign &&
1672 DL->getTypeAllocSize(GV->getValueType()) >=
1673 MinSize + Offset2)
1674 GV->setAlignment(PrefAlign);
1676 // If this is a memcpy (or similar) then we may be able to improve the
1677 // alignment
1678 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
1679 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1680 if (DestAlign > MI->getDestAlignment())
1681 MI->setDestAlignment(DestAlign);
1682 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1683 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1684 if (SrcAlign > MTI->getSourceAlignment())
1685 MTI->setSourceAlignment(SrcAlign);
1690 // If we have a cold call site, try to sink addressing computation into the
1691 // cold block. This interacts with our handling for loads and stores to
1692 // ensure that we can fold all uses of a potential addressing computation
1693 // into their uses. TODO: generalize this to work over profiling data
1694 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1695 for (auto &Arg : CI->arg_operands()) {
1696 if (!Arg->getType()->isPointerTy())
1697 continue;
1698 unsigned AS = Arg->getType()->getPointerAddressSpace();
1699 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1702 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
1703 if (II) {
1704 switch (II->getIntrinsicID()) {
1705 default: break;
1706 case Intrinsic::objectsize: {
1707 // Lower all uses of llvm.objectsize.*
1708 ConstantInt *RetVal =
1709 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
1711 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1712 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1714 return true;
1716 case Intrinsic::is_constant: {
1717 // If is_constant hasn't folded away yet, lower it to false now.
1718 Constant *RetVal = ConstantInt::get(II->getType(), 0);
1719 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1720 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1722 return true;
1724 case Intrinsic::aarch64_stlxr:
1725 case Intrinsic::aarch64_stxr: {
1726 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1727 if (!ExtVal || !ExtVal->hasOneUse() ||
1728 ExtVal->getParent() == CI->getParent())
1729 return false;
1730 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1731 ExtVal->moveBefore(CI);
1732 // Mark this instruction as "inserted by CGP", so that other
1733 // optimizations don't touch it.
1734 InsertedInsts.insert(ExtVal);
1735 return true;
1737 case Intrinsic::launder_invariant_group:
1738 case Intrinsic::strip_invariant_group: {
1739 Value *ArgVal = II->getArgOperand(0);
1740 auto it = LargeOffsetGEPMap.find(II);
1741 if (it != LargeOffsetGEPMap.end()) {
1742 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
1743 // Make sure not to have to deal with iterator invalidation
1744 // after possibly adding ArgVal to LargeOffsetGEPMap.
1745 auto GEPs = std::move(it->second);
1746 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
1747 LargeOffsetGEPMap.erase(II);
1750 II->replaceAllUsesWith(ArgVal);
1751 II->eraseFromParent();
1752 return true;
1754 case Intrinsic::cttz:
1755 case Intrinsic::ctlz:
1756 // If counting zeros is expensive, try to avoid it.
1757 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
1760 if (TLI) {
1761 SmallVector<Value*, 2> PtrOps;
1762 Type *AccessTy;
1763 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1764 while (!PtrOps.empty()) {
1765 Value *PtrVal = PtrOps.pop_back_val();
1766 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1767 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
1768 return true;
1773 // From here on out we're working with named functions.
1774 if (!CI->getCalledFunction()) return false;
1776 // Lower all default uses of _chk calls. This is very similar
1777 // to what InstCombineCalls does, but here we are only lowering calls
1778 // to fortified library functions (e.g. __memcpy_chk) that have the default
1779 // "don't know" as the objectsize. Anything else should be left alone.
1780 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
1781 if (Value *V = Simplifier.optimizeCall(CI)) {
1782 CI->replaceAllUsesWith(V);
1783 CI->eraseFromParent();
1784 return true;
1787 return false;
1790 /// Look for opportunities to duplicate return instructions to the predecessor
1791 /// to enable tail call optimizations. The case it is currently looking for is:
1792 /// @code
1793 /// bb0:
1794 /// %tmp0 = tail call i32 @f0()
1795 /// br label %return
1796 /// bb1:
1797 /// %tmp1 = tail call i32 @f1()
1798 /// br label %return
1799 /// bb2:
1800 /// %tmp2 = tail call i32 @f2()
1801 /// br label %return
1802 /// return:
1803 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1804 /// ret i32 %retval
1805 /// @endcode
1807 /// =>
1809 /// @code
1810 /// bb0:
1811 /// %tmp0 = tail call i32 @f0()
1812 /// ret i32 %tmp0
1813 /// bb1:
1814 /// %tmp1 = tail call i32 @f1()
1815 /// ret i32 %tmp1
1816 /// bb2:
1817 /// %tmp2 = tail call i32 @f2()
1818 /// ret i32 %tmp2
1819 /// @endcode
1820 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
1821 if (!TLI)
1822 return false;
1824 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1825 if (!RetI)
1826 return false;
1828 PHINode *PN = nullptr;
1829 BitCastInst *BCI = nullptr;
1830 Value *V = RetI->getReturnValue();
1831 if (V) {
1832 BCI = dyn_cast<BitCastInst>(V);
1833 if (BCI)
1834 V = BCI->getOperand(0);
1836 PN = dyn_cast<PHINode>(V);
1837 if (!PN)
1838 return false;
1841 if (PN && PN->getParent() != BB)
1842 return false;
1844 // Make sure there are no instructions between the PHI and return, or that the
1845 // return is the first instruction in the block.
1846 if (PN) {
1847 BasicBlock::iterator BI = BB->begin();
1848 // Skip over debug and the bitcast.
1849 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI);
1850 if (&*BI != RetI)
1851 return false;
1852 } else {
1853 BasicBlock::iterator BI = BB->begin();
1854 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1855 if (&*BI != RetI)
1856 return false;
1859 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1860 /// call.
1861 const Function *F = BB->getParent();
1862 SmallVector<CallInst*, 4> TailCalls;
1863 if (PN) {
1864 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1865 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1866 // Make sure the phi value is indeed produced by the tail call.
1867 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1868 TLI->mayBeEmittedAsTailCall(CI) &&
1869 attributesPermitTailCall(F, CI, RetI, *TLI))
1870 TailCalls.push_back(CI);
1872 } else {
1873 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1874 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1875 if (!VisitedBBs.insert(*PI).second)
1876 continue;
1878 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1879 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1880 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1881 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1882 if (RI == RE)
1883 continue;
1885 CallInst *CI = dyn_cast<CallInst>(&*RI);
1886 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1887 attributesPermitTailCall(F, CI, RetI, *TLI))
1888 TailCalls.push_back(CI);
1892 bool Changed = false;
1893 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1894 CallInst *CI = TailCalls[i];
1895 CallSite CS(CI);
1897 // Make sure the call instruction is followed by an unconditional branch to
1898 // the return block.
1899 BasicBlock *CallBB = CI->getParent();
1900 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1901 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1902 continue;
1904 // Duplicate the return into CallBB.
1905 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
1906 ModifiedDT = Changed = true;
1907 ++NumRetsDup;
1910 // If we eliminated all predecessors of the block, delete the block now.
1911 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1912 BB->eraseFromParent();
1914 return Changed;
1917 //===----------------------------------------------------------------------===//
1918 // Memory Optimization
1919 //===----------------------------------------------------------------------===//
1921 namespace {
1923 /// This is an extended version of TargetLowering::AddrMode
1924 /// which holds actual Value*'s for register values.
1925 struct ExtAddrMode : public TargetLowering::AddrMode {
1926 Value *BaseReg = nullptr;
1927 Value *ScaledReg = nullptr;
1928 Value *OriginalValue = nullptr;
1930 enum FieldName {
1931 NoField = 0x00,
1932 BaseRegField = 0x01,
1933 BaseGVField = 0x02,
1934 BaseOffsField = 0x04,
1935 ScaledRegField = 0x08,
1936 ScaleField = 0x10,
1937 MultipleFields = 0xff
1940 ExtAddrMode() = default;
1942 void print(raw_ostream &OS) const;
1943 void dump() const;
1945 FieldName compare(const ExtAddrMode &other) {
1946 // First check that the types are the same on each field, as differing types
1947 // is something we can't cope with later on.
1948 if (BaseReg && other.BaseReg &&
1949 BaseReg->getType() != other.BaseReg->getType())
1950 return MultipleFields;
1951 if (BaseGV && other.BaseGV &&
1952 BaseGV->getType() != other.BaseGV->getType())
1953 return MultipleFields;
1954 if (ScaledReg && other.ScaledReg &&
1955 ScaledReg->getType() != other.ScaledReg->getType())
1956 return MultipleFields;
1958 // Check each field to see if it differs.
1959 unsigned Result = NoField;
1960 if (BaseReg != other.BaseReg)
1961 Result |= BaseRegField;
1962 if (BaseGV != other.BaseGV)
1963 Result |= BaseGVField;
1964 if (BaseOffs != other.BaseOffs)
1965 Result |= BaseOffsField;
1966 if (ScaledReg != other.ScaledReg)
1967 Result |= ScaledRegField;
1968 // Don't count 0 as being a different scale, because that actually means
1969 // unscaled (which will already be counted by having no ScaledReg).
1970 if (Scale && other.Scale && Scale != other.Scale)
1971 Result |= ScaleField;
1973 if (countPopulation(Result) > 1)
1974 return MultipleFields;
1975 else
1976 return static_cast<FieldName>(Result);
1979 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1980 // with no offset.
1981 bool isTrivial() {
1982 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1983 // trivial if at most one of these terms is nonzero, except that BaseGV and
1984 // BaseReg both being zero actually means a null pointer value, which we
1985 // consider to be 'non-zero' here.
1986 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
1989 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1990 switch (Field) {
1991 default:
1992 return nullptr;
1993 case BaseRegField:
1994 return BaseReg;
1995 case BaseGVField:
1996 return BaseGV;
1997 case ScaledRegField:
1998 return ScaledReg;
1999 case BaseOffsField:
2000 return ConstantInt::get(IntPtrTy, BaseOffs);
2004 void SetCombinedField(FieldName Field, Value *V,
2005 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2006 switch (Field) {
2007 default:
2008 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2009 break;
2010 case ExtAddrMode::BaseRegField:
2011 BaseReg = V;
2012 break;
2013 case ExtAddrMode::BaseGVField:
2014 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2015 // in the BaseReg field.
2016 assert(BaseReg == nullptr);
2017 BaseReg = V;
2018 BaseGV = nullptr;
2019 break;
2020 case ExtAddrMode::ScaledRegField:
2021 ScaledReg = V;
2022 // If we have a mix of scaled and unscaled addrmodes then we want scale
2023 // to be the scale and not zero.
2024 if (!Scale)
2025 for (const ExtAddrMode &AM : AddrModes)
2026 if (AM.Scale) {
2027 Scale = AM.Scale;
2028 break;
2030 break;
2031 case ExtAddrMode::BaseOffsField:
2032 // The offset is no longer a constant, so it goes in ScaledReg with a
2033 // scale of 1.
2034 assert(ScaledReg == nullptr);
2035 ScaledReg = V;
2036 Scale = 1;
2037 BaseOffs = 0;
2038 break;
2043 } // end anonymous namespace
2045 #ifndef NDEBUG
2046 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2047 AM.print(OS);
2048 return OS;
2050 #endif
2052 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2053 void ExtAddrMode::print(raw_ostream &OS) const {
2054 bool NeedPlus = false;
2055 OS << "[";
2056 if (BaseGV) {
2057 OS << (NeedPlus ? " + " : "")
2058 << "GV:";
2059 BaseGV->printAsOperand(OS, /*PrintType=*/false);
2060 NeedPlus = true;
2063 if (BaseOffs) {
2064 OS << (NeedPlus ? " + " : "")
2065 << BaseOffs;
2066 NeedPlus = true;
2069 if (BaseReg) {
2070 OS << (NeedPlus ? " + " : "")
2071 << "Base:";
2072 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2073 NeedPlus = true;
2075 if (Scale) {
2076 OS << (NeedPlus ? " + " : "")
2077 << Scale << "*";
2078 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2081 OS << ']';
2084 LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
2085 print(dbgs());
2086 dbgs() << '\n';
2088 #endif
2090 namespace {
2092 /// This class provides transaction based operation on the IR.
2093 /// Every change made through this class is recorded in the internal state and
2094 /// can be undone (rollback) until commit is called.
2095 class TypePromotionTransaction {
2096 /// This represents the common interface of the individual transaction.
2097 /// Each class implements the logic for doing one specific modification on
2098 /// the IR via the TypePromotionTransaction.
2099 class TypePromotionAction {
2100 protected:
2101 /// The Instruction modified.
2102 Instruction *Inst;
2104 public:
2105 /// Constructor of the action.
2106 /// The constructor performs the related action on the IR.
2107 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2109 virtual ~TypePromotionAction() = default;
2111 /// Undo the modification done by this action.
2112 /// When this method is called, the IR must be in the same state as it was
2113 /// before this action was applied.
2114 /// \pre Undoing the action works if and only if the IR is in the exact same
2115 /// state as it was directly after this action was applied.
2116 virtual void undo() = 0;
2118 /// Advocate every change made by this action.
2119 /// When the results on the IR of the action are to be kept, it is important
2120 /// to call this function, otherwise hidden information may be kept forever.
2121 virtual void commit() {
2122 // Nothing to be done, this action is not doing anything.
2126 /// Utility to remember the position of an instruction.
2127 class InsertionHandler {
2128 /// Position of an instruction.
2129 /// Either an instruction:
2130 /// - Is the first in a basic block: BB is used.
2131 /// - Has a previous instruction: PrevInst is used.
2132 union {
2133 Instruction *PrevInst;
2134 BasicBlock *BB;
2135 } Point;
2137 /// Remember whether or not the instruction had a previous instruction.
2138 bool HasPrevInstruction;
2140 public:
2141 /// Record the position of \p Inst.
2142 InsertionHandler(Instruction *Inst) {
2143 BasicBlock::iterator It = Inst->getIterator();
2144 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2145 if (HasPrevInstruction)
2146 Point.PrevInst = &*--It;
2147 else
2148 Point.BB = Inst->getParent();
2151 /// Insert \p Inst at the recorded position.
2152 void insert(Instruction *Inst) {
2153 if (HasPrevInstruction) {
2154 if (Inst->getParent())
2155 Inst->removeFromParent();
2156 Inst->insertAfter(Point.PrevInst);
2157 } else {
2158 Instruction *Position = &*Point.BB->getFirstInsertionPt();
2159 if (Inst->getParent())
2160 Inst->moveBefore(Position);
2161 else
2162 Inst->insertBefore(Position);
2167 /// Move an instruction before another.
2168 class InstructionMoveBefore : public TypePromotionAction {
2169 /// Original position of the instruction.
2170 InsertionHandler Position;
2172 public:
2173 /// Move \p Inst before \p Before.
2174 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2175 : TypePromotionAction(Inst), Position(Inst) {
2176 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2177 << "\n");
2178 Inst->moveBefore(Before);
2181 /// Move the instruction back to its original position.
2182 void undo() override {
2183 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2184 Position.insert(Inst);
2188 /// Set the operand of an instruction with a new value.
2189 class OperandSetter : public TypePromotionAction {
2190 /// Original operand of the instruction.
2191 Value *Origin;
2193 /// Index of the modified instruction.
2194 unsigned Idx;
2196 public:
2197 /// Set \p Idx operand of \p Inst with \p NewVal.
2198 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2199 : TypePromotionAction(Inst), Idx(Idx) {
2200 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2201 << "for:" << *Inst << "\n"
2202 << "with:" << *NewVal << "\n");
2203 Origin = Inst->getOperand(Idx);
2204 Inst->setOperand(Idx, NewVal);
2207 /// Restore the original value of the instruction.
2208 void undo() override {
2209 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2210 << "for: " << *Inst << "\n"
2211 << "with: " << *Origin << "\n");
2212 Inst->setOperand(Idx, Origin);
2216 /// Hide the operands of an instruction.
2217 /// Do as if this instruction was not using any of its operands.
2218 class OperandsHider : public TypePromotionAction {
2219 /// The list of original operands.
2220 SmallVector<Value *, 4> OriginalValues;
2222 public:
2223 /// Remove \p Inst from the uses of the operands of \p Inst.
2224 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2225 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2226 unsigned NumOpnds = Inst->getNumOperands();
2227 OriginalValues.reserve(NumOpnds);
2228 for (unsigned It = 0; It < NumOpnds; ++It) {
2229 // Save the current operand.
2230 Value *Val = Inst->getOperand(It);
2231 OriginalValues.push_back(Val);
2232 // Set a dummy one.
2233 // We could use OperandSetter here, but that would imply an overhead
2234 // that we are not willing to pay.
2235 Inst->setOperand(It, UndefValue::get(Val->getType()));
2239 /// Restore the original list of uses.
2240 void undo() override {
2241 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2242 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2243 Inst->setOperand(It, OriginalValues[It]);
2247 /// Build a truncate instruction.
2248 class TruncBuilder : public TypePromotionAction {
2249 Value *Val;
2251 public:
2252 /// Build a truncate instruction of \p Opnd producing a \p Ty
2253 /// result.
2254 /// trunc Opnd to Ty.
2255 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2256 IRBuilder<> Builder(Opnd);
2257 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2258 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
2261 /// Get the built value.
2262 Value *getBuiltValue() { return Val; }
2264 /// Remove the built instruction.
2265 void undo() override {
2266 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2267 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2268 IVal->eraseFromParent();
2272 /// Build a sign extension instruction.
2273 class SExtBuilder : public TypePromotionAction {
2274 Value *Val;
2276 public:
2277 /// Build a sign extension instruction of \p Opnd producing a \p Ty
2278 /// result.
2279 /// sext Opnd to Ty.
2280 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2281 : TypePromotionAction(InsertPt) {
2282 IRBuilder<> Builder(InsertPt);
2283 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2284 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
2287 /// Get the built value.
2288 Value *getBuiltValue() { return Val; }
2290 /// Remove the built instruction.
2291 void undo() override {
2292 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2293 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2294 IVal->eraseFromParent();
2298 /// Build a zero extension instruction.
2299 class ZExtBuilder : public TypePromotionAction {
2300 Value *Val;
2302 public:
2303 /// Build a zero extension instruction of \p Opnd producing a \p Ty
2304 /// result.
2305 /// zext Opnd to Ty.
2306 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2307 : TypePromotionAction(InsertPt) {
2308 IRBuilder<> Builder(InsertPt);
2309 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2310 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
2313 /// Get the built value.
2314 Value *getBuiltValue() { return Val; }
2316 /// Remove the built instruction.
2317 void undo() override {
2318 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2319 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2320 IVal->eraseFromParent();
2324 /// Mutate an instruction to another type.
2325 class TypeMutator : public TypePromotionAction {
2326 /// Record the original type.
2327 Type *OrigTy;
2329 public:
2330 /// Mutate the type of \p Inst into \p NewTy.
2331 TypeMutator(Instruction *Inst, Type *NewTy)
2332 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2333 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2334 << "\n");
2335 Inst->mutateType(NewTy);
2338 /// Mutate the instruction back to its original type.
2339 void undo() override {
2340 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2341 << "\n");
2342 Inst->mutateType(OrigTy);
2346 /// Replace the uses of an instruction by another instruction.
2347 class UsesReplacer : public TypePromotionAction {
2348 /// Helper structure to keep track of the replaced uses.
2349 struct InstructionAndIdx {
2350 /// The instruction using the instruction.
2351 Instruction *Inst;
2353 /// The index where this instruction is used for Inst.
2354 unsigned Idx;
2356 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2357 : Inst(Inst), Idx(Idx) {}
2360 /// Keep track of the original uses (pair Instruction, Index).
2361 SmallVector<InstructionAndIdx, 4> OriginalUses;
2362 /// Keep track of the debug users.
2363 SmallVector<DbgValueInst *, 1> DbgValues;
2365 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
2367 public:
2368 /// Replace all the use of \p Inst by \p New.
2369 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2370 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2371 << "\n");
2372 // Record the original uses.
2373 for (Use &U : Inst->uses()) {
2374 Instruction *UserI = cast<Instruction>(U.getUser());
2375 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2377 // Record the debug uses separately. They are not in the instruction's
2378 // use list, but they are replaced by RAUW.
2379 findDbgValues(DbgValues, Inst);
2381 // Now, we can replace the uses.
2382 Inst->replaceAllUsesWith(New);
2385 /// Reassign the original uses of Inst to Inst.
2386 void undo() override {
2387 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2388 for (use_iterator UseIt = OriginalUses.begin(),
2389 EndIt = OriginalUses.end();
2390 UseIt != EndIt; ++UseIt) {
2391 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2393 // RAUW has replaced all original uses with references to the new value,
2394 // including the debug uses. Since we are undoing the replacements,
2395 // the original debug uses must also be reinstated to maintain the
2396 // correctness and utility of debug value instructions.
2397 for (auto *DVI: DbgValues) {
2398 LLVMContext &Ctx = Inst->getType()->getContext();
2399 auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst));
2400 DVI->setOperand(0, MV);
2405 /// Remove an instruction from the IR.
2406 class InstructionRemover : public TypePromotionAction {
2407 /// Original position of the instruction.
2408 InsertionHandler Inserter;
2410 /// Helper structure to hide all the link to the instruction. In other
2411 /// words, this helps to do as if the instruction was removed.
2412 OperandsHider Hider;
2414 /// Keep track of the uses replaced, if any.
2415 UsesReplacer *Replacer = nullptr;
2417 /// Keep track of instructions removed.
2418 SetOfInstrs &RemovedInsts;
2420 public:
2421 /// Remove all reference of \p Inst and optionally replace all its
2422 /// uses with New.
2423 /// \p RemovedInsts Keep track of the instructions removed by this Action.
2424 /// \pre If !Inst->use_empty(), then New != nullptr
2425 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2426 Value *New = nullptr)
2427 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
2428 RemovedInsts(RemovedInsts) {
2429 if (New)
2430 Replacer = new UsesReplacer(Inst, New);
2431 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2432 RemovedInsts.insert(Inst);
2433 /// The instructions removed here will be freed after completing
2434 /// optimizeBlock() for all blocks as we need to keep track of the
2435 /// removed instructions during promotion.
2436 Inst->removeFromParent();
2439 ~InstructionRemover() override { delete Replacer; }
2441 /// Resurrect the instruction and reassign it to the proper uses if
2442 /// new value was provided when build this action.
2443 void undo() override {
2444 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2445 Inserter.insert(Inst);
2446 if (Replacer)
2447 Replacer->undo();
2448 Hider.undo();
2449 RemovedInsts.erase(Inst);
2453 public:
2454 /// Restoration point.
2455 /// The restoration point is a pointer to an action instead of an iterator
2456 /// because the iterator may be invalidated but not the pointer.
2457 using ConstRestorationPt = const TypePromotionAction *;
2459 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2460 : RemovedInsts(RemovedInsts) {}
2462 /// Advocate every changes made in that transaction.
2463 void commit();
2465 /// Undo all the changes made after the given point.
2466 void rollback(ConstRestorationPt Point);
2468 /// Get the current restoration point.
2469 ConstRestorationPt getRestorationPoint() const;
2471 /// \name API for IR modification with state keeping to support rollback.
2472 /// @{
2473 /// Same as Instruction::setOperand.
2474 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2476 /// Same as Instruction::eraseFromParent.
2477 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
2479 /// Same as Value::replaceAllUsesWith.
2480 void replaceAllUsesWith(Instruction *Inst, Value *New);
2482 /// Same as Value::mutateType.
2483 void mutateType(Instruction *Inst, Type *NewTy);
2485 /// Same as IRBuilder::createTrunc.
2486 Value *createTrunc(Instruction *Opnd, Type *Ty);
2488 /// Same as IRBuilder::createSExt.
2489 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
2491 /// Same as IRBuilder::createZExt.
2492 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
2494 /// Same as Instruction::moveBefore.
2495 void moveBefore(Instruction *Inst, Instruction *Before);
2496 /// @}
2498 private:
2499 /// The ordered list of actions made so far.
2500 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2502 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2504 SetOfInstrs &RemovedInsts;
2507 } // end anonymous namespace
2509 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2510 Value *NewVal) {
2511 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2512 Inst, Idx, NewVal));
2515 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2516 Value *NewVal) {
2517 Actions.push_back(
2518 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2519 Inst, RemovedInsts, NewVal));
2522 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2523 Value *New) {
2524 Actions.push_back(
2525 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
2528 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
2529 Actions.push_back(
2530 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
2533 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2534 Type *Ty) {
2535 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
2536 Value *Val = Ptr->getBuiltValue();
2537 Actions.push_back(std::move(Ptr));
2538 return Val;
2541 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2542 Value *Opnd, Type *Ty) {
2543 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
2544 Value *Val = Ptr->getBuiltValue();
2545 Actions.push_back(std::move(Ptr));
2546 return Val;
2549 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2550 Value *Opnd, Type *Ty) {
2551 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
2552 Value *Val = Ptr->getBuiltValue();
2553 Actions.push_back(std::move(Ptr));
2554 return Val;
2557 void TypePromotionTransaction::moveBefore(Instruction *Inst,
2558 Instruction *Before) {
2559 Actions.push_back(
2560 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2561 Inst, Before));
2564 TypePromotionTransaction::ConstRestorationPt
2565 TypePromotionTransaction::getRestorationPoint() const {
2566 return !Actions.empty() ? Actions.back().get() : nullptr;
2569 void TypePromotionTransaction::commit() {
2570 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
2571 ++It)
2572 (*It)->commit();
2573 Actions.clear();
2576 void TypePromotionTransaction::rollback(
2577 TypePromotionTransaction::ConstRestorationPt Point) {
2578 while (!Actions.empty() && Point != Actions.back().get()) {
2579 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
2580 Curr->undo();
2584 namespace {
2586 /// A helper class for matching addressing modes.
2588 /// This encapsulates the logic for matching the target-legal addressing modes.
2589 class AddressingModeMatcher {
2590 SmallVectorImpl<Instruction*> &AddrModeInsts;
2591 const TargetLowering &TLI;
2592 const TargetRegisterInfo &TRI;
2593 const DataLayout &DL;
2595 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2596 /// the memory instruction that we're computing this address for.
2597 Type *AccessTy;
2598 unsigned AddrSpace;
2599 Instruction *MemoryInst;
2601 /// This is the addressing mode that we're building up. This is
2602 /// part of the return value of this addressing mode matching stuff.
2603 ExtAddrMode &AddrMode;
2605 /// The instructions inserted by other CodeGenPrepare optimizations.
2606 const SetOfInstrs &InsertedInsts;
2608 /// A map from the instructions to their type before promotion.
2609 InstrToOrigTy &PromotedInsts;
2611 /// The ongoing transaction where every action should be registered.
2612 TypePromotionTransaction &TPT;
2614 // A GEP which has too large offset to be folded into the addressing mode.
2615 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2617 /// This is set to true when we should not do profitability checks.
2618 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
2619 bool IgnoreProfitability;
2621 AddressingModeMatcher(
2622 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2623 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2624 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2625 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2626 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
2627 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
2628 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2629 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2630 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
2631 IgnoreProfitability = false;
2634 public:
2635 /// Find the maximal addressing mode that a load/store of V can fold,
2636 /// give an access type of AccessTy. This returns a list of involved
2637 /// instructions in AddrModeInsts.
2638 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
2639 /// optimizations.
2640 /// \p PromotedInsts maps the instructions to their type before promotion.
2641 /// \p The ongoing transaction where every action should be registered.
2642 static ExtAddrMode
2643 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2644 SmallVectorImpl<Instruction *> &AddrModeInsts,
2645 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2646 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2647 TypePromotionTransaction &TPT,
2648 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
2649 ExtAddrMode Result;
2651 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
2652 MemoryInst, Result, InsertedInsts,
2653 PromotedInsts, TPT, LargeOffsetGEP)
2654 .matchAddr(V, 0);
2655 (void)Success; assert(Success && "Couldn't select *anything*?");
2656 return Result;
2659 private:
2660 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2661 bool matchAddr(Value *Addr, unsigned Depth);
2662 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
2663 bool *MovedAway = nullptr);
2664 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
2665 ExtAddrMode &AMBefore,
2666 ExtAddrMode &AMAfter);
2667 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2668 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
2669 Value *PromotedOperand) const;
2672 class PhiNodeSet;
2674 /// An iterator for PhiNodeSet.
2675 class PhiNodeSetIterator {
2676 PhiNodeSet * const Set;
2677 size_t CurrentIndex = 0;
2679 public:
2680 /// The constructor. Start should point to either a valid element, or be equal
2681 /// to the size of the underlying SmallVector of the PhiNodeSet.
2682 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
2683 PHINode * operator*() const;
2684 PhiNodeSetIterator& operator++();
2685 bool operator==(const PhiNodeSetIterator &RHS) const;
2686 bool operator!=(const PhiNodeSetIterator &RHS) const;
2689 /// Keeps a set of PHINodes.
2691 /// This is a minimal set implementation for a specific use case:
2692 /// It is very fast when there are very few elements, but also provides good
2693 /// performance when there are many. It is similar to SmallPtrSet, but also
2694 /// provides iteration by insertion order, which is deterministic and stable
2695 /// across runs. It is also similar to SmallSetVector, but provides removing
2696 /// elements in O(1) time. This is achieved by not actually removing the element
2697 /// from the underlying vector, so comes at the cost of using more memory, but
2698 /// that is fine, since PhiNodeSets are used as short lived objects.
2699 class PhiNodeSet {
2700 friend class PhiNodeSetIterator;
2702 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
2703 using iterator = PhiNodeSetIterator;
2705 /// Keeps the elements in the order of their insertion in the underlying
2706 /// vector. To achieve constant time removal, it never deletes any element.
2707 SmallVector<PHINode *, 32> NodeList;
2709 /// Keeps the elements in the underlying set implementation. This (and not the
2710 /// NodeList defined above) is the source of truth on whether an element
2711 /// is actually in the collection.
2712 MapType NodeMap;
2714 /// Points to the first valid (not deleted) element when the set is not empty
2715 /// and the value is not zero. Equals to the size of the underlying vector
2716 /// when the set is empty. When the value is 0, as in the beginning, the
2717 /// first element may or may not be valid.
2718 size_t FirstValidElement = 0;
2720 public:
2721 /// Inserts a new element to the collection.
2722 /// \returns true if the element is actually added, i.e. was not in the
2723 /// collection before the operation.
2724 bool insert(PHINode *Ptr) {
2725 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
2726 NodeList.push_back(Ptr);
2727 return true;
2729 return false;
2732 /// Removes the element from the collection.
2733 /// \returns whether the element is actually removed, i.e. was in the
2734 /// collection before the operation.
2735 bool erase(PHINode *Ptr) {
2736 auto it = NodeMap.find(Ptr);
2737 if (it != NodeMap.end()) {
2738 NodeMap.erase(Ptr);
2739 SkipRemovedElements(FirstValidElement);
2740 return true;
2742 return false;
2745 /// Removes all elements and clears the collection.
2746 void clear() {
2747 NodeMap.clear();
2748 NodeList.clear();
2749 FirstValidElement = 0;
2752 /// \returns an iterator that will iterate the elements in the order of
2753 /// insertion.
2754 iterator begin() {
2755 if (FirstValidElement == 0)
2756 SkipRemovedElements(FirstValidElement);
2757 return PhiNodeSetIterator(this, FirstValidElement);
2760 /// \returns an iterator that points to the end of the collection.
2761 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
2763 /// Returns the number of elements in the collection.
2764 size_t size() const {
2765 return NodeMap.size();
2768 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
2769 size_t count(PHINode *Ptr) const {
2770 return NodeMap.count(Ptr);
2773 private:
2774 /// Updates the CurrentIndex so that it will point to a valid element.
2776 /// If the element of NodeList at CurrentIndex is valid, it does not
2777 /// change it. If there are no more valid elements, it updates CurrentIndex
2778 /// to point to the end of the NodeList.
2779 void SkipRemovedElements(size_t &CurrentIndex) {
2780 while (CurrentIndex < NodeList.size()) {
2781 auto it = NodeMap.find(NodeList[CurrentIndex]);
2782 // If the element has been deleted and added again later, NodeMap will
2783 // point to a different index, so CurrentIndex will still be invalid.
2784 if (it != NodeMap.end() && it->second == CurrentIndex)
2785 break;
2786 ++CurrentIndex;
2791 PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
2792 : Set(Set), CurrentIndex(Start) {}
2794 PHINode * PhiNodeSetIterator::operator*() const {
2795 assert(CurrentIndex < Set->NodeList.size() &&
2796 "PhiNodeSet access out of range");
2797 return Set->NodeList[CurrentIndex];
2800 PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
2801 assert(CurrentIndex < Set->NodeList.size() &&
2802 "PhiNodeSet access out of range");
2803 ++CurrentIndex;
2804 Set->SkipRemovedElements(CurrentIndex);
2805 return *this;
2808 bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
2809 return CurrentIndex == RHS.CurrentIndex;
2812 bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
2813 return !((*this) == RHS);
2816 /// Keep track of simplification of Phi nodes.
2817 /// Accept the set of all phi nodes and erase phi node from this set
2818 /// if it is simplified.
2819 class SimplificationTracker {
2820 DenseMap<Value *, Value *> Storage;
2821 const SimplifyQuery &SQ;
2822 // Tracks newly created Phi nodes. The elements are iterated by insertion
2823 // order.
2824 PhiNodeSet AllPhiNodes;
2825 // Tracks newly created Select nodes.
2826 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
2828 public:
2829 SimplificationTracker(const SimplifyQuery &sq)
2830 : SQ(sq) {}
2832 Value *Get(Value *V) {
2833 do {
2834 auto SV = Storage.find(V);
2835 if (SV == Storage.end())
2836 return V;
2837 V = SV->second;
2838 } while (true);
2841 Value *Simplify(Value *Val) {
2842 SmallVector<Value *, 32> WorkList;
2843 SmallPtrSet<Value *, 32> Visited;
2844 WorkList.push_back(Val);
2845 while (!WorkList.empty()) {
2846 auto P = WorkList.pop_back_val();
2847 if (!Visited.insert(P).second)
2848 continue;
2849 if (auto *PI = dyn_cast<Instruction>(P))
2850 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2851 for (auto *U : PI->users())
2852 WorkList.push_back(cast<Value>(U));
2853 Put(PI, V);
2854 PI->replaceAllUsesWith(V);
2855 if (auto *PHI = dyn_cast<PHINode>(PI))
2856 AllPhiNodes.erase(PHI);
2857 if (auto *Select = dyn_cast<SelectInst>(PI))
2858 AllSelectNodes.erase(Select);
2859 PI->eraseFromParent();
2862 return Get(Val);
2865 void Put(Value *From, Value *To) {
2866 Storage.insert({ From, To });
2869 void ReplacePhi(PHINode *From, PHINode *To) {
2870 Value* OldReplacement = Get(From);
2871 while (OldReplacement != From) {
2872 From = To;
2873 To = dyn_cast<PHINode>(OldReplacement);
2874 OldReplacement = Get(From);
2876 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2877 Put(From, To);
2878 From->replaceAllUsesWith(To);
2879 AllPhiNodes.erase(From);
2880 From->eraseFromParent();
2883 PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
2885 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2887 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2889 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2891 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2893 void destroyNewNodes(Type *CommonType) {
2894 // For safe erasing, replace the uses with dummy value first.
2895 auto Dummy = UndefValue::get(CommonType);
2896 for (auto I : AllPhiNodes) {
2897 I->replaceAllUsesWith(Dummy);
2898 I->eraseFromParent();
2900 AllPhiNodes.clear();
2901 for (auto I : AllSelectNodes) {
2902 I->replaceAllUsesWith(Dummy);
2903 I->eraseFromParent();
2905 AllSelectNodes.clear();
2909 /// A helper class for combining addressing modes.
2910 class AddressingModeCombiner {
2911 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
2912 typedef std::pair<PHINode *, PHINode *> PHIPair;
2914 private:
2915 /// The addressing modes we've collected.
2916 SmallVector<ExtAddrMode, 16> AddrModes;
2918 /// The field in which the AddrModes differ, when we have more than one.
2919 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2921 /// Are the AddrModes that we have all just equal to their original values?
2922 bool AllAddrModesTrivial = true;
2924 /// Common Type for all different fields in addressing modes.
2925 Type *CommonType;
2927 /// SimplifyQuery for simplifyInstruction utility.
2928 const SimplifyQuery &SQ;
2930 /// Original Address.
2931 Value *Original;
2933 public:
2934 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
2935 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2937 /// Get the combined AddrMode
2938 const ExtAddrMode &getAddrMode() const {
2939 return AddrModes[0];
2942 /// Add a new AddrMode if it's compatible with the AddrModes we already
2943 /// have.
2944 /// \return True iff we succeeded in doing so.
2945 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2946 // Take note of if we have any non-trivial AddrModes, as we need to detect
2947 // when all AddrModes are trivial as then we would introduce a phi or select
2948 // which just duplicates what's already there.
2949 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2951 // If this is the first addrmode then everything is fine.
2952 if (AddrModes.empty()) {
2953 AddrModes.emplace_back(NewAddrMode);
2954 return true;
2957 // Figure out how different this is from the other address modes, which we
2958 // can do just by comparing against the first one given that we only care
2959 // about the cumulative difference.
2960 ExtAddrMode::FieldName ThisDifferentField =
2961 AddrModes[0].compare(NewAddrMode);
2962 if (DifferentField == ExtAddrMode::NoField)
2963 DifferentField = ThisDifferentField;
2964 else if (DifferentField != ThisDifferentField)
2965 DifferentField = ExtAddrMode::MultipleFields;
2967 // If NewAddrMode differs in more than one dimension we cannot handle it.
2968 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2970 // If Scale Field is different then we reject.
2971 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2973 // We also must reject the case when base offset is different and
2974 // scale reg is not null, we cannot handle this case due to merge of
2975 // different offsets will be used as ScaleReg.
2976 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2977 !NewAddrMode.ScaledReg);
2979 // We also must reject the case when GV is different and BaseReg installed
2980 // due to we want to use base reg as a merge of GV values.
2981 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2982 !NewAddrMode.HasBaseReg);
2984 // Even if NewAddMode is the same we still need to collect it due to
2985 // original value is different. And later we will need all original values
2986 // as anchors during finding the common Phi node.
2987 if (CanHandle)
2988 AddrModes.emplace_back(NewAddrMode);
2989 else
2990 AddrModes.clear();
2992 return CanHandle;
2995 /// Combine the addressing modes we've collected into a single
2996 /// addressing mode.
2997 /// \return True iff we successfully combined them or we only had one so
2998 /// didn't need to combine them anyway.
2999 bool combineAddrModes() {
3000 // If we have no AddrModes then they can't be combined.
3001 if (AddrModes.size() == 0)
3002 return false;
3004 // A single AddrMode can trivially be combined.
3005 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
3006 return true;
3008 // If the AddrModes we collected are all just equal to the value they are
3009 // derived from then combining them wouldn't do anything useful.
3010 if (AllAddrModesTrivial)
3011 return false;
3013 if (!addrModeCombiningAllowed())
3014 return false;
3016 // Build a map between <original value, basic block where we saw it> to
3017 // value of base register.
3018 // Bail out if there is no common type.
3019 FoldAddrToValueMapping Map;
3020 if (!initializeMap(Map))
3021 return false;
3023 Value *CommonValue = findCommon(Map);
3024 if (CommonValue)
3025 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
3026 return CommonValue != nullptr;
3029 private:
3030 /// Initialize Map with anchor values. For address seen
3031 /// we set the value of different field saw in this address.
3032 /// At the same time we find a common type for different field we will
3033 /// use to create new Phi/Select nodes. Keep it in CommonType field.
3034 /// Return false if there is no common type found.
3035 bool initializeMap(FoldAddrToValueMapping &Map) {
3036 // Keep track of keys where the value is null. We will need to replace it
3037 // with constant null when we know the common type.
3038 SmallVector<Value *, 2> NullValue;
3039 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
3040 for (auto &AM : AddrModes) {
3041 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
3042 if (DV) {
3043 auto *Type = DV->getType();
3044 if (CommonType && CommonType != Type)
3045 return false;
3046 CommonType = Type;
3047 Map[AM.OriginalValue] = DV;
3048 } else {
3049 NullValue.push_back(AM.OriginalValue);
3052 assert(CommonType && "At least one non-null value must be!");
3053 for (auto *V : NullValue)
3054 Map[V] = Constant::getNullValue(CommonType);
3055 return true;
3058 /// We have mapping between value A and other value B where B was a field in
3059 /// addressing mode represented by A. Also we have an original value C
3060 /// representing an address we start with. Traversing from C through phi and
3061 /// selects we ended up with A's in a map. This utility function tries to find
3062 /// a value V which is a field in addressing mode C and traversing through phi
3063 /// nodes and selects we will end up in corresponded values B in a map.
3064 /// The utility will create a new Phi/Selects if needed.
3065 // The simple example looks as follows:
3066 // BB1:
3067 // p1 = b1 + 40
3068 // br cond BB2, BB3
3069 // BB2:
3070 // p2 = b2 + 40
3071 // br BB3
3072 // BB3:
3073 // p = phi [p1, BB1], [p2, BB2]
3074 // v = load p
3075 // Map is
3076 // p1 -> b1
3077 // p2 -> b2
3078 // Request is
3079 // p -> ?
3080 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
3081 Value *findCommon(FoldAddrToValueMapping &Map) {
3082 // Tracks the simplification of newly created phi nodes. The reason we use
3083 // this mapping is because we will add new created Phi nodes in AddrToBase.
3084 // Simplification of Phi nodes is recursive, so some Phi node may
3085 // be simplified after we added it to AddrToBase. In reality this
3086 // simplification is possible only if original phi/selects were not
3087 // simplified yet.
3088 // Using this mapping we can find the current value in AddrToBase.
3089 SimplificationTracker ST(SQ);
3091 // First step, DFS to create PHI nodes for all intermediate blocks.
3092 // Also fill traverse order for the second step.
3093 SmallVector<Value *, 32> TraverseOrder;
3094 InsertPlaceholders(Map, TraverseOrder, ST);
3096 // Second Step, fill new nodes by merged values and simplify if possible.
3097 FillPlaceholders(Map, TraverseOrder, ST);
3099 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3100 ST.destroyNewNodes(CommonType);
3101 return nullptr;
3104 // Now we'd like to match New Phi nodes to existed ones.
3105 unsigned PhiNotMatchedCount = 0;
3106 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3107 ST.destroyNewNodes(CommonType);
3108 return nullptr;
3111 auto *Result = ST.Get(Map.find(Original)->second);
3112 if (Result) {
3113 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3114 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
3116 return Result;
3119 /// Try to match PHI node to Candidate.
3120 /// Matcher tracks the matched Phi nodes.
3121 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
3122 SmallSetVector<PHIPair, 8> &Matcher,
3123 PhiNodeSet &PhiNodesToMatch) {
3124 SmallVector<PHIPair, 8> WorkList;
3125 Matcher.insert({ PHI, Candidate });
3126 WorkList.push_back({ PHI, Candidate });
3127 SmallSet<PHIPair, 8> Visited;
3128 while (!WorkList.empty()) {
3129 auto Item = WorkList.pop_back_val();
3130 if (!Visited.insert(Item).second)
3131 continue;
3132 // We iterate over all incoming values to Phi to compare them.
3133 // If values are different and both of them Phi and the first one is a
3134 // Phi we added (subject to match) and both of them is in the same basic
3135 // block then we can match our pair if values match. So we state that
3136 // these values match and add it to work list to verify that.
3137 for (auto B : Item.first->blocks()) {
3138 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3139 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3140 if (FirstValue == SecondValue)
3141 continue;
3143 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3144 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3146 // One of them is not Phi or
3147 // The first one is not Phi node from the set we'd like to match or
3148 // Phi nodes from different basic blocks then
3149 // we will not be able to match.
3150 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3151 FirstPhi->getParent() != SecondPhi->getParent())
3152 return false;
3154 // If we already matched them then continue.
3155 if (Matcher.count({ FirstPhi, SecondPhi }))
3156 continue;
3157 // So the values are different and does not match. So we need them to
3158 // match.
3159 Matcher.insert({ FirstPhi, SecondPhi });
3160 // But me must check it.
3161 WorkList.push_back({ FirstPhi, SecondPhi });
3164 return true;
3167 /// For the given set of PHI nodes (in the SimplificationTracker) try
3168 /// to find their equivalents.
3169 /// Returns false if this matching fails and creation of new Phi is disabled.
3170 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
3171 unsigned &PhiNotMatchedCount) {
3172 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3173 // order, so the replacements (ReplacePhi) are also done in a deterministic
3174 // order.
3175 SmallSetVector<PHIPair, 8> Matched;
3176 SmallPtrSet<PHINode *, 8> WillNotMatch;
3177 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
3178 while (PhiNodesToMatch.size()) {
3179 PHINode *PHI = *PhiNodesToMatch.begin();
3181 // Add us, if no Phi nodes in the basic block we do not match.
3182 WillNotMatch.clear();
3183 WillNotMatch.insert(PHI);
3185 // Traverse all Phis until we found equivalent or fail to do that.
3186 bool IsMatched = false;
3187 for (auto &P : PHI->getParent()->phis()) {
3188 if (&P == PHI)
3189 continue;
3190 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3191 break;
3192 // If it does not match, collect all Phi nodes from matcher.
3193 // if we end up with no match, them all these Phi nodes will not match
3194 // later.
3195 for (auto M : Matched)
3196 WillNotMatch.insert(M.first);
3197 Matched.clear();
3199 if (IsMatched) {
3200 // Replace all matched values and erase them.
3201 for (auto MV : Matched)
3202 ST.ReplacePhi(MV.first, MV.second);
3203 Matched.clear();
3204 continue;
3206 // If we are not allowed to create new nodes then bail out.
3207 if (!AllowNewPhiNodes)
3208 return false;
3209 // Just remove all seen values in matcher. They will not match anything.
3210 PhiNotMatchedCount += WillNotMatch.size();
3211 for (auto *P : WillNotMatch)
3212 PhiNodesToMatch.erase(P);
3214 return true;
3216 /// Fill the placeholders with values from predecessors and simplify them.
3217 void FillPlaceholders(FoldAddrToValueMapping &Map,
3218 SmallVectorImpl<Value *> &TraverseOrder,
3219 SimplificationTracker &ST) {
3220 while (!TraverseOrder.empty()) {
3221 Value *Current = TraverseOrder.pop_back_val();
3222 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3223 Value *V = Map[Current];
3225 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3226 // CurrentValue also must be Select.
3227 auto *CurrentSelect = cast<SelectInst>(Current);
3228 auto *TrueValue = CurrentSelect->getTrueValue();
3229 assert(Map.find(TrueValue) != Map.end() && "No True Value!");
3230 Select->setTrueValue(ST.Get(Map[TrueValue]));
3231 auto *FalseValue = CurrentSelect->getFalseValue();
3232 assert(Map.find(FalseValue) != Map.end() && "No False Value!");
3233 Select->setFalseValue(ST.Get(Map[FalseValue]));
3234 } else {
3235 // Must be a Phi node then.
3236 PHINode *PHI = cast<PHINode>(V);
3237 auto *CurrentPhi = dyn_cast<PHINode>(Current);
3238 // Fill the Phi node with values from predecessors.
3239 for (auto B : predecessors(PHI->getParent())) {
3240 Value *PV = CurrentPhi->getIncomingValueForBlock(B);
3241 assert(Map.find(PV) != Map.end() && "No predecessor Value!");
3242 PHI->addIncoming(ST.Get(Map[PV]), B);
3245 Map[Current] = ST.Simplify(V);
3249 /// Starting from original value recursively iterates over def-use chain up to
3250 /// known ending values represented in a map. For each traversed phi/select
3251 /// inserts a placeholder Phi or Select.
3252 /// Reports all new created Phi/Select nodes by adding them to set.
3253 /// Also reports and order in what values have been traversed.
3254 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3255 SmallVectorImpl<Value *> &TraverseOrder,
3256 SimplificationTracker &ST) {
3257 SmallVector<Value *, 32> Worklist;
3258 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
3259 "Address must be a Phi or Select node");
3260 auto *Dummy = UndefValue::get(CommonType);
3261 Worklist.push_back(Original);
3262 while (!Worklist.empty()) {
3263 Value *Current = Worklist.pop_back_val();
3264 // if it is already visited or it is an ending value then skip it.
3265 if (Map.find(Current) != Map.end())
3266 continue;
3267 TraverseOrder.push_back(Current);
3269 // CurrentValue must be a Phi node or select. All others must be covered
3270 // by anchors.
3271 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
3272 // Is it OK to get metadata from OrigSelect?!
3273 // Create a Select placeholder with dummy value.
3274 SelectInst *Select = SelectInst::Create(
3275 CurrentSelect->getCondition(), Dummy, Dummy,
3276 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
3277 Map[Current] = Select;
3278 ST.insertNewSelect(Select);
3279 // We are interested in True and False values.
3280 Worklist.push_back(CurrentSelect->getTrueValue());
3281 Worklist.push_back(CurrentSelect->getFalseValue());
3282 } else {
3283 // It must be a Phi node then.
3284 PHINode *CurrentPhi = cast<PHINode>(Current);
3285 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3286 PHINode *PHI =
3287 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
3288 Map[Current] = PHI;
3289 ST.insertNewPhi(PHI);
3290 for (Value *P : CurrentPhi->incoming_values())
3291 Worklist.push_back(P);
3296 bool addrModeCombiningAllowed() {
3297 if (DisableComplexAddrModes)
3298 return false;
3299 switch (DifferentField) {
3300 default:
3301 return false;
3302 case ExtAddrMode::BaseRegField:
3303 return AddrSinkCombineBaseReg;
3304 case ExtAddrMode::BaseGVField:
3305 return AddrSinkCombineBaseGV;
3306 case ExtAddrMode::BaseOffsField:
3307 return AddrSinkCombineBaseOffs;
3308 case ExtAddrMode::ScaledRegField:
3309 return AddrSinkCombineScaledReg;
3313 } // end anonymous namespace
3315 /// Try adding ScaleReg*Scale to the current addressing mode.
3316 /// Return true and update AddrMode if this addr mode is legal for the target,
3317 /// false if not.
3318 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3319 unsigned Depth) {
3320 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3321 // mode. Just process that directly.
3322 if (Scale == 1)
3323 return matchAddr(ScaleReg, Depth);
3325 // If the scale is 0, it takes nothing to add this.
3326 if (Scale == 0)
3327 return true;
3329 // If we already have a scale of this value, we can add to it, otherwise, we
3330 // need an available scale field.
3331 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3332 return false;
3334 ExtAddrMode TestAddrMode = AddrMode;
3336 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3337 // [A+B + A*7] -> [B+A*8].
3338 TestAddrMode.Scale += Scale;
3339 TestAddrMode.ScaledReg = ScaleReg;
3341 // If the new address isn't legal, bail out.
3342 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3343 return false;
3345 // It was legal, so commit it.
3346 AddrMode = TestAddrMode;
3348 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3349 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3350 // X*Scale + C*Scale to addr mode.
3351 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3352 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3353 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3354 TestAddrMode.ScaledReg = AddLHS;
3355 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
3357 // If this addressing mode is legal, commit it and remember that we folded
3358 // this instruction.
3359 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3360 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3361 AddrMode = TestAddrMode;
3362 return true;
3366 // Otherwise, not (x+c)*scale, just return what we have.
3367 return true;
3370 /// This is a little filter, which returns true if an addressing computation
3371 /// involving I might be folded into a load/store accessing it.
3372 /// This doesn't need to be perfect, but needs to accept at least
3373 /// the set of instructions that MatchOperationAddr can.
3374 static bool MightBeFoldableInst(Instruction *I) {
3375 switch (I->getOpcode()) {
3376 case Instruction::BitCast:
3377 case Instruction::AddrSpaceCast:
3378 // Don't touch identity bitcasts.
3379 if (I->getType() == I->getOperand(0)->getType())
3380 return false;
3381 return I->getType()->isIntOrPtrTy();
3382 case Instruction::PtrToInt:
3383 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3384 return true;
3385 case Instruction::IntToPtr:
3386 // We know the input is intptr_t, so this is foldable.
3387 return true;
3388 case Instruction::Add:
3389 return true;
3390 case Instruction::Mul:
3391 case Instruction::Shl:
3392 // Can only handle X*C and X << C.
3393 return isa<ConstantInt>(I->getOperand(1));
3394 case Instruction::GetElementPtr:
3395 return true;
3396 default:
3397 return false;
3401 /// Check whether or not \p Val is a legal instruction for \p TLI.
3402 /// \note \p Val is assumed to be the product of some type promotion.
3403 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3404 /// to be legal, as the non-promoted value would have had the same state.
3405 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3406 const DataLayout &DL, Value *Val) {
3407 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3408 if (!PromotedInst)
3409 return false;
3410 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3411 // If the ISDOpcode is undefined, it was undefined before the promotion.
3412 if (!ISDOpcode)
3413 return true;
3414 // Otherwise, check if the promoted instruction is legal or not.
3415 return TLI.isOperationLegalOrCustom(
3416 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
3419 namespace {
3421 /// Hepler class to perform type promotion.
3422 class TypePromotionHelper {
3423 /// Utility function to add a promoted instruction \p ExtOpnd to
3424 /// \p PromotedInsts and record the type of extension we have seen.
3425 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3426 Instruction *ExtOpnd,
3427 bool IsSExt) {
3428 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3429 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3430 if (It != PromotedInsts.end()) {
3431 // If the new extension is same as original, the information in
3432 // PromotedInsts[ExtOpnd] is still correct.
3433 if (It->second.getInt() == ExtTy)
3434 return;
3436 // Now the new extension is different from old extension, we make
3437 // the type information invalid by setting extension type to
3438 // BothExtension.
3439 ExtTy = BothExtension;
3441 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
3444 /// Utility function to query the original type of instruction \p Opnd
3445 /// with a matched extension type. If the extension doesn't match, we
3446 /// cannot use the information we had on the original type.
3447 /// BothExtension doesn't match any extension type.
3448 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
3449 Instruction *Opnd,
3450 bool IsSExt) {
3451 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3452 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3453 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3454 return It->second.getPointer();
3455 return nullptr;
3458 /// Utility function to check whether or not a sign or zero extension
3459 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3460 /// either using the operands of \p Inst or promoting \p Inst.
3461 /// The type of the extension is defined by \p IsSExt.
3462 /// In other words, check if:
3463 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
3464 /// #1 Promotion applies:
3465 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
3466 /// #2 Operand reuses:
3467 /// ext opnd1 to ConsideredExtType.
3468 /// \p PromotedInsts maps the instructions to their type before promotion.
3469 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3470 const InstrToOrigTy &PromotedInsts, bool IsSExt);
3472 /// Utility function to determine if \p OpIdx should be promoted when
3473 /// promoting \p Inst.
3474 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
3475 return !(isa<SelectInst>(Inst) && OpIdx == 0);
3478 /// Utility function to promote the operand of \p Ext when this
3479 /// operand is a promotable trunc or sext or zext.
3480 /// \p PromotedInsts maps the instructions to their type before promotion.
3481 /// \p CreatedInstsCost[out] contains the cost of all instructions
3482 /// created to promote the operand of Ext.
3483 /// Newly added extensions are inserted in \p Exts.
3484 /// Newly added truncates are inserted in \p Truncs.
3485 /// Should never be called directly.
3486 /// \return The promoted value which is used instead of Ext.
3487 static Value *promoteOperandForTruncAndAnyExt(
3488 Instruction *Ext, TypePromotionTransaction &TPT,
3489 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3490 SmallVectorImpl<Instruction *> *Exts,
3491 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
3493 /// Utility function to promote the operand of \p Ext when this
3494 /// operand is promotable and is not a supported trunc or sext.
3495 /// \p PromotedInsts maps the instructions to their type before promotion.
3496 /// \p CreatedInstsCost[out] contains the cost of all the instructions
3497 /// created to promote the operand of Ext.
3498 /// Newly added extensions are inserted in \p Exts.
3499 /// Newly added truncates are inserted in \p Truncs.
3500 /// Should never be called directly.
3501 /// \return The promoted value which is used instead of Ext.
3502 static Value *promoteOperandForOther(Instruction *Ext,
3503 TypePromotionTransaction &TPT,
3504 InstrToOrigTy &PromotedInsts,
3505 unsigned &CreatedInstsCost,
3506 SmallVectorImpl<Instruction *> *Exts,
3507 SmallVectorImpl<Instruction *> *Truncs,
3508 const TargetLowering &TLI, bool IsSExt);
3510 /// \see promoteOperandForOther.
3511 static Value *signExtendOperandForOther(
3512 Instruction *Ext, TypePromotionTransaction &TPT,
3513 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3514 SmallVectorImpl<Instruction *> *Exts,
3515 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3516 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3517 Exts, Truncs, TLI, true);
3520 /// \see promoteOperandForOther.
3521 static Value *zeroExtendOperandForOther(
3522 Instruction *Ext, TypePromotionTransaction &TPT,
3523 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3524 SmallVectorImpl<Instruction *> *Exts,
3525 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3526 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3527 Exts, Truncs, TLI, false);
3530 public:
3531 /// Type for the utility function that promotes the operand of Ext.
3532 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3533 InstrToOrigTy &PromotedInsts,
3534 unsigned &CreatedInstsCost,
3535 SmallVectorImpl<Instruction *> *Exts,
3536 SmallVectorImpl<Instruction *> *Truncs,
3537 const TargetLowering &TLI);
3539 /// Given a sign/zero extend instruction \p Ext, return the appropriate
3540 /// action to promote the operand of \p Ext instead of using Ext.
3541 /// \return NULL if no promotable action is possible with the current
3542 /// sign extension.
3543 /// \p InsertedInsts keeps track of all the instructions inserted by the
3544 /// other CodeGenPrepare optimizations. This information is important
3545 /// because we do not want to promote these instructions as CodeGenPrepare
3546 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3547 /// \p PromotedInsts maps the instructions to their type before promotion.
3548 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
3549 const TargetLowering &TLI,
3550 const InstrToOrigTy &PromotedInsts);
3553 } // end anonymous namespace
3555 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
3556 Type *ConsideredExtType,
3557 const InstrToOrigTy &PromotedInsts,
3558 bool IsSExt) {
3559 // The promotion helper does not know how to deal with vector types yet.
3560 // To be able to fix that, we would need to fix the places where we
3561 // statically extend, e.g., constants and such.
3562 if (Inst->getType()->isVectorTy())
3563 return false;
3565 // We can always get through zext.
3566 if (isa<ZExtInst>(Inst))
3567 return true;
3569 // sext(sext) is ok too.
3570 if (IsSExt && isa<SExtInst>(Inst))
3571 return true;
3573 // We can get through binary operator, if it is legal. In other words, the
3574 // binary operator must have a nuw or nsw flag.
3575 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3576 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3577 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3578 (IsSExt && BinOp->hasNoSignedWrap())))
3579 return true;
3581 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3582 if ((Inst->getOpcode() == Instruction::And ||
3583 Inst->getOpcode() == Instruction::Or))
3584 return true;
3586 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3587 if (Inst->getOpcode() == Instruction::Xor) {
3588 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3589 // Make sure it is not a NOT.
3590 if (Cst && !Cst->getValue().isAllOnesValue())
3591 return true;
3594 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3595 // It may change a poisoned value into a regular value, like
3596 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3597 // poisoned value regular value
3598 // It should be OK since undef covers valid value.
3599 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3600 return true;
3602 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3603 // It may change a poisoned value into a regular value, like
3604 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3605 // poisoned value regular value
3606 // It should be OK since undef covers valid value.
3607 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3608 const Instruction *ExtInst =
3609 dyn_cast<const Instruction>(*Inst->user_begin());
3610 if (ExtInst->hasOneUse()) {
3611 const Instruction *AndInst =
3612 dyn_cast<const Instruction>(*ExtInst->user_begin());
3613 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3614 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3615 if (Cst &&
3616 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3617 return true;
3622 // Check if we can do the following simplification.
3623 // ext(trunc(opnd)) --> ext(opnd)
3624 if (!isa<TruncInst>(Inst))
3625 return false;
3627 Value *OpndVal = Inst->getOperand(0);
3628 // Check if we can use this operand in the extension.
3629 // If the type is larger than the result type of the extension, we cannot.
3630 if (!OpndVal->getType()->isIntegerTy() ||
3631 OpndVal->getType()->getIntegerBitWidth() >
3632 ConsideredExtType->getIntegerBitWidth())
3633 return false;
3635 // If the operand of the truncate is not an instruction, we will not have
3636 // any information on the dropped bits.
3637 // (Actually we could for constant but it is not worth the extra logic).
3638 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3639 if (!Opnd)
3640 return false;
3642 // Check if the source of the type is narrow enough.
3643 // I.e., check that trunc just drops extended bits of the same kind of
3644 // the extension.
3645 // #1 get the type of the operand and check the kind of the extended bits.
3646 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3647 if (OpndType)
3649 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3650 OpndType = Opnd->getOperand(0)->getType();
3651 else
3652 return false;
3654 // #2 check that the truncate just drops extended bits.
3655 return Inst->getType()->getIntegerBitWidth() >=
3656 OpndType->getIntegerBitWidth();
3659 TypePromotionHelper::Action TypePromotionHelper::getAction(
3660 Instruction *Ext, const SetOfInstrs &InsertedInsts,
3661 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3662 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3663 "Unexpected instruction type");
3664 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3665 Type *ExtTy = Ext->getType();
3666 bool IsSExt = isa<SExtInst>(Ext);
3667 // If the operand of the extension is not an instruction, we cannot
3668 // get through.
3669 // If it, check we can get through.
3670 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3671 return nullptr;
3673 // Do not promote if the operand has been added by codegenprepare.
3674 // Otherwise, it means we are undoing an optimization that is likely to be
3675 // redone, thus causing potential infinite loop.
3676 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3677 return nullptr;
3679 // SExt or Trunc instructions.
3680 // Return the related handler.
3681 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3682 isa<ZExtInst>(ExtOpnd))
3683 return promoteOperandForTruncAndAnyExt;
3685 // Regular instruction.
3686 // Abort early if we will have to insert non-free instructions.
3687 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
3688 return nullptr;
3689 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3692 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3693 Instruction *SExt, TypePromotionTransaction &TPT,
3694 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3695 SmallVectorImpl<Instruction *> *Exts,
3696 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3697 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3698 // get through it and this method should not be called.
3699 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
3700 Value *ExtVal = SExt;
3701 bool HasMergedNonFreeExt = false;
3702 if (isa<ZExtInst>(SExtOpnd)) {
3703 // Replace s|zext(zext(opnd))
3704 // => zext(opnd).
3705 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
3706 Value *ZExt =
3707 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3708 TPT.replaceAllUsesWith(SExt, ZExt);
3709 TPT.eraseInstruction(SExt);
3710 ExtVal = ZExt;
3711 } else {
3712 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3713 // => z|sext(opnd).
3714 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3716 CreatedInstsCost = 0;
3718 // Remove dead code.
3719 if (SExtOpnd->use_empty())
3720 TPT.eraseInstruction(SExtOpnd);
3722 // Check if the extension is still needed.
3723 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
3724 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3725 if (ExtInst) {
3726 if (Exts)
3727 Exts->push_back(ExtInst);
3728 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3730 return ExtVal;
3733 // At this point we have: ext ty opnd to ty.
3734 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3735 Value *NextVal = ExtInst->getOperand(0);
3736 TPT.eraseInstruction(ExtInst, NextVal);
3737 return NextVal;
3740 Value *TypePromotionHelper::promoteOperandForOther(
3741 Instruction *Ext, TypePromotionTransaction &TPT,
3742 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3743 SmallVectorImpl<Instruction *> *Exts,
3744 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3745 bool IsSExt) {
3746 // By construction, the operand of Ext is an instruction. Otherwise we cannot
3747 // get through it and this method should not be called.
3748 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3749 CreatedInstsCost = 0;
3750 if (!ExtOpnd->hasOneUse()) {
3751 // ExtOpnd will be promoted.
3752 // All its uses, but Ext, will need to use a truncated value of the
3753 // promoted version.
3754 // Create the truncate now.
3755 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
3756 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3757 // Insert it just after the definition.
3758 ITrunc->moveAfter(ExtOpnd);
3759 if (Truncs)
3760 Truncs->push_back(ITrunc);
3763 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
3764 // Restore the operand of Ext (which has been replaced by the previous call
3765 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
3766 TPT.setOperand(Ext, 0, ExtOpnd);
3769 // Get through the Instruction:
3770 // 1. Update its type.
3771 // 2. Replace the uses of Ext by Inst.
3772 // 3. Extend each operand that needs to be extended.
3774 // Remember the original type of the instruction before promotion.
3775 // This is useful to know that the high bits are sign extended bits.
3776 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
3777 // Step #1.
3778 TPT.mutateType(ExtOpnd, Ext->getType());
3779 // Step #2.
3780 TPT.replaceAllUsesWith(Ext, ExtOpnd);
3781 // Step #3.
3782 Instruction *ExtForOpnd = Ext;
3784 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
3785 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
3786 ++OpIdx) {
3787 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3788 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3789 !shouldExtOperand(ExtOpnd, OpIdx)) {
3790 LLVM_DEBUG(dbgs() << "No need to propagate\n");
3791 continue;
3793 // Check if we can statically extend the operand.
3794 Value *Opnd = ExtOpnd->getOperand(OpIdx);
3795 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
3796 LLVM_DEBUG(dbgs() << "Statically extend\n");
3797 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3798 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3799 : Cst->getValue().zext(BitWidth);
3800 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
3801 continue;
3803 // UndefValue are typed, so we have to statically sign extend them.
3804 if (isa<UndefValue>(Opnd)) {
3805 LLVM_DEBUG(dbgs() << "Statically extend\n");
3806 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
3807 continue;
3810 // Otherwise we have to explicitly sign extend the operand.
3811 // Check if Ext was reused to extend an operand.
3812 if (!ExtForOpnd) {
3813 // If yes, create a new one.
3814 LLVM_DEBUG(dbgs() << "More operands to ext\n");
3815 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3816 : TPT.createZExt(Ext, Opnd, Ext->getType());
3817 if (!isa<Instruction>(ValForExtOpnd)) {
3818 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3819 continue;
3821 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
3823 if (Exts)
3824 Exts->push_back(ExtForOpnd);
3825 TPT.setOperand(ExtForOpnd, 0, Opnd);
3827 // Move the sign extension before the insertion point.
3828 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3829 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3830 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
3831 // If more sext are required, new instructions will have to be created.
3832 ExtForOpnd = nullptr;
3834 if (ExtForOpnd == Ext) {
3835 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
3836 TPT.eraseInstruction(Ext);
3838 return ExtOpnd;
3841 /// Check whether or not promoting an instruction to a wider type is profitable.
3842 /// \p NewCost gives the cost of extension instructions created by the
3843 /// promotion.
3844 /// \p OldCost gives the cost of extension instructions before the promotion
3845 /// plus the number of instructions that have been
3846 /// matched in the addressing mode the promotion.
3847 /// \p PromotedOperand is the value that has been promoted.
3848 /// \return True if the promotion is profitable, false otherwise.
3849 bool AddressingModeMatcher::isPromotionProfitable(
3850 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3851 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
3852 << '\n');
3853 // The cost of the new extensions is greater than the cost of the
3854 // old extension plus what we folded.
3855 // This is not profitable.
3856 if (NewCost > OldCost)
3857 return false;
3858 if (NewCost < OldCost)
3859 return true;
3860 // The promotion is neutral but it may help folding the sign extension in
3861 // loads for instance.
3862 // Check that we did not create an illegal instruction.
3863 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
3866 /// Given an instruction or constant expr, see if we can fold the operation
3867 /// into the addressing mode. If so, update the addressing mode and return
3868 /// true, otherwise return false without modifying AddrMode.
3869 /// If \p MovedAway is not NULL, it contains the information of whether or
3870 /// not AddrInst has to be folded into the addressing mode on success.
3871 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3872 /// because it has been moved away.
3873 /// Thus AddrInst must not be added in the matched instructions.
3874 /// This state can happen when AddrInst is a sext, since it may be moved away.
3875 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
3876 /// not be referenced anymore.
3877 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
3878 unsigned Depth,
3879 bool *MovedAway) {
3880 // Avoid exponential behavior on extremely deep expression trees.
3881 if (Depth >= 5) return false;
3883 // By default, all matched instructions stay in place.
3884 if (MovedAway)
3885 *MovedAway = false;
3887 switch (Opcode) {
3888 case Instruction::PtrToInt:
3889 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3890 return matchAddr(AddrInst->getOperand(0), Depth);
3891 case Instruction::IntToPtr: {
3892 auto AS = AddrInst->getType()->getPointerAddressSpace();
3893 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
3894 // This inttoptr is a no-op if the integer type is pointer sized.
3895 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
3896 return matchAddr(AddrInst->getOperand(0), Depth);
3897 return false;
3899 case Instruction::BitCast:
3900 // BitCast is always a noop, and we can handle it as long as it is
3901 // int->int or pointer->pointer (we don't want int<->fp or something).
3902 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
3903 // Don't touch identity bitcasts. These were probably put here by LSR,
3904 // and we don't want to mess around with them. Assume it knows what it
3905 // is doing.
3906 AddrInst->getOperand(0)->getType() != AddrInst->getType())
3907 return matchAddr(AddrInst->getOperand(0), Depth);
3908 return false;
3909 case Instruction::AddrSpaceCast: {
3910 unsigned SrcAS
3911 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3912 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3913 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3914 return matchAddr(AddrInst->getOperand(0), Depth);
3915 return false;
3917 case Instruction::Add: {
3918 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3919 ExtAddrMode BackupAddrMode = AddrMode;
3920 unsigned OldSize = AddrModeInsts.size();
3921 // Start a transaction at this point.
3922 // The LHS may match but not the RHS.
3923 // Therefore, we need a higher level restoration point to undo partially
3924 // matched operation.
3925 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3926 TPT.getRestorationPoint();
3928 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3929 matchAddr(AddrInst->getOperand(0), Depth+1))
3930 return true;
3932 // Restore the old addr mode info.
3933 AddrMode = BackupAddrMode;
3934 AddrModeInsts.resize(OldSize);
3935 TPT.rollback(LastKnownGood);
3937 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
3938 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3939 matchAddr(AddrInst->getOperand(1), Depth+1))
3940 return true;
3942 // Otherwise we definitely can't merge the ADD in.
3943 AddrMode = BackupAddrMode;
3944 AddrModeInsts.resize(OldSize);
3945 TPT.rollback(LastKnownGood);
3946 break;
3948 //case Instruction::Or:
3949 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3950 //break;
3951 case Instruction::Mul:
3952 case Instruction::Shl: {
3953 // Can only handle X*C and X << C.
3954 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
3955 if (!RHS || RHS->getBitWidth() > 64)
3956 return false;
3957 int64_t Scale = RHS->getSExtValue();
3958 if (Opcode == Instruction::Shl)
3959 Scale = 1LL << Scale;
3961 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
3963 case Instruction::GetElementPtr: {
3964 // Scan the GEP. We check it if it contains constant offsets and at most
3965 // one variable offset.
3966 int VariableOperand = -1;
3967 unsigned VariableScale = 0;
3969 int64_t ConstantOffset = 0;
3970 gep_type_iterator GTI = gep_type_begin(AddrInst);
3971 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3972 if (StructType *STy = GTI.getStructTypeOrNull()) {
3973 const StructLayout *SL = DL.getStructLayout(STy);
3974 unsigned Idx =
3975 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3976 ConstantOffset += SL->getElementOffset(Idx);
3977 } else {
3978 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
3979 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3980 const APInt &CVal = CI->getValue();
3981 if (CVal.getMinSignedBits() <= 64) {
3982 ConstantOffset += CVal.getSExtValue() * TypeSize;
3983 continue;
3986 if (TypeSize) { // Scales of zero don't do anything.
3987 // We only allow one variable index at the moment.
3988 if (VariableOperand != -1)
3989 return false;
3991 // Remember the variable index.
3992 VariableOperand = i;
3993 VariableScale = TypeSize;
3998 // A common case is for the GEP to only do a constant offset. In this case,
3999 // just add it to the disp field and check validity.
4000 if (VariableOperand == -1) {
4001 AddrMode.BaseOffs += ConstantOffset;
4002 if (ConstantOffset == 0 ||
4003 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4004 // Check to see if we can fold the base pointer in too.
4005 if (matchAddr(AddrInst->getOperand(0), Depth+1))
4006 return true;
4007 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4008 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4009 ConstantOffset > 0) {
4010 // Record GEPs with non-zero offsets as candidates for splitting in the
4011 // event that the offset cannot fit into the r+i addressing mode.
4012 // Simple and common case that only one GEP is used in calculating the
4013 // address for the memory access.
4014 Value *Base = AddrInst->getOperand(0);
4015 auto *BaseI = dyn_cast<Instruction>(Base);
4016 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4017 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4018 (BaseI && !isa<CastInst>(BaseI) &&
4019 !isa<GetElementPtrInst>(BaseI))) {
4020 // If the base is an instruction, make sure the GEP is not in the same
4021 // basic block as the base. If the base is an argument or global
4022 // value, make sure the GEP is not in the entry block. Otherwise,
4023 // instruction selection can undo the split. Also make sure the
4024 // parent block allows inserting non-PHI instructions before the
4025 // terminator.
4026 BasicBlock *Parent =
4027 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4028 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
4029 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4032 AddrMode.BaseOffs -= ConstantOffset;
4033 return false;
4036 // Save the valid addressing mode in case we can't match.
4037 ExtAddrMode BackupAddrMode = AddrMode;
4038 unsigned OldSize = AddrModeInsts.size();
4040 // See if the scale and offset amount is valid for this target.
4041 AddrMode.BaseOffs += ConstantOffset;
4043 // Match the base operand of the GEP.
4044 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
4045 // If it couldn't be matched, just stuff the value in a register.
4046 if (AddrMode.HasBaseReg) {
4047 AddrMode = BackupAddrMode;
4048 AddrModeInsts.resize(OldSize);
4049 return false;
4051 AddrMode.HasBaseReg = true;
4052 AddrMode.BaseReg = AddrInst->getOperand(0);
4055 // Match the remaining variable portion of the GEP.
4056 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4057 Depth)) {
4058 // If it couldn't be matched, try stuffing the base into a register
4059 // instead of matching it, and retrying the match of the scale.
4060 AddrMode = BackupAddrMode;
4061 AddrModeInsts.resize(OldSize);
4062 if (AddrMode.HasBaseReg)
4063 return false;
4064 AddrMode.HasBaseReg = true;
4065 AddrMode.BaseReg = AddrInst->getOperand(0);
4066 AddrMode.BaseOffs += ConstantOffset;
4067 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4068 VariableScale, Depth)) {
4069 // If even that didn't work, bail.
4070 AddrMode = BackupAddrMode;
4071 AddrModeInsts.resize(OldSize);
4072 return false;
4076 return true;
4078 case Instruction::SExt:
4079 case Instruction::ZExt: {
4080 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4081 if (!Ext)
4082 return false;
4084 // Try to move this ext out of the way of the addressing mode.
4085 // Ask for a method for doing so.
4086 TypePromotionHelper::Action TPH =
4087 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4088 if (!TPH)
4089 return false;
4091 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4092 TPT.getRestorationPoint();
4093 unsigned CreatedInstsCost = 0;
4094 unsigned ExtCost = !TLI.isExtFree(Ext);
4095 Value *PromotedOperand =
4096 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4097 // SExt has been moved away.
4098 // Thus either it will be rematched later in the recursive calls or it is
4099 // gone. Anyway, we must not fold it into the addressing mode at this point.
4100 // E.g.,
4101 // op = add opnd, 1
4102 // idx = ext op
4103 // addr = gep base, idx
4104 // is now:
4105 // promotedOpnd = ext opnd <- no match here
4106 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4107 // addr = gep base, op <- match
4108 if (MovedAway)
4109 *MovedAway = true;
4111 assert(PromotedOperand &&
4112 "TypePromotionHelper should have filtered out those cases");
4114 ExtAddrMode BackupAddrMode = AddrMode;
4115 unsigned OldSize = AddrModeInsts.size();
4117 if (!matchAddr(PromotedOperand, Depth) ||
4118 // The total of the new cost is equal to the cost of the created
4119 // instructions.
4120 // The total of the old cost is equal to the cost of the extension plus
4121 // what we have saved in the addressing mode.
4122 !isPromotionProfitable(CreatedInstsCost,
4123 ExtCost + (AddrModeInsts.size() - OldSize),
4124 PromotedOperand)) {
4125 AddrMode = BackupAddrMode;
4126 AddrModeInsts.resize(OldSize);
4127 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
4128 TPT.rollback(LastKnownGood);
4129 return false;
4131 return true;
4134 return false;
4137 /// If we can, try to add the value of 'Addr' into the current addressing mode.
4138 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4139 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
4140 /// for the target.
4142 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4143 // Start a transaction at this point that we will rollback if the matching
4144 // fails.
4145 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4146 TPT.getRestorationPoint();
4147 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4148 // Fold in immediates if legal for the target.
4149 AddrMode.BaseOffs += CI->getSExtValue();
4150 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4151 return true;
4152 AddrMode.BaseOffs -= CI->getSExtValue();
4153 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4154 // If this is a global variable, try to fold it into the addressing mode.
4155 if (!AddrMode.BaseGV) {
4156 AddrMode.BaseGV = GV;
4157 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4158 return true;
4159 AddrMode.BaseGV = nullptr;
4161 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4162 ExtAddrMode BackupAddrMode = AddrMode;
4163 unsigned OldSize = AddrModeInsts.size();
4165 // Check to see if it is possible to fold this operation.
4166 bool MovedAway = false;
4167 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4168 // This instruction may have been moved away. If so, there is nothing
4169 // to check here.
4170 if (MovedAway)
4171 return true;
4172 // Okay, it's possible to fold this. Check to see if it is actually
4173 // *profitable* to do so. We use a simple cost model to avoid increasing
4174 // register pressure too much.
4175 if (I->hasOneUse() ||
4176 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4177 AddrModeInsts.push_back(I);
4178 return true;
4181 // It isn't profitable to do this, roll back.
4182 //cerr << "NOT FOLDING: " << *I;
4183 AddrMode = BackupAddrMode;
4184 AddrModeInsts.resize(OldSize);
4185 TPT.rollback(LastKnownGood);
4187 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4188 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4189 return true;
4190 TPT.rollback(LastKnownGood);
4191 } else if (isa<ConstantPointerNull>(Addr)) {
4192 // Null pointer gets folded without affecting the addressing mode.
4193 return true;
4196 // Worse case, the target should support [reg] addressing modes. :)
4197 if (!AddrMode.HasBaseReg) {
4198 AddrMode.HasBaseReg = true;
4199 AddrMode.BaseReg = Addr;
4200 // Still check for legality in case the target supports [imm] but not [i+r].
4201 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4202 return true;
4203 AddrMode.HasBaseReg = false;
4204 AddrMode.BaseReg = nullptr;
4207 // If the base register is already taken, see if we can do [r+r].
4208 if (AddrMode.Scale == 0) {
4209 AddrMode.Scale = 1;
4210 AddrMode.ScaledReg = Addr;
4211 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4212 return true;
4213 AddrMode.Scale = 0;
4214 AddrMode.ScaledReg = nullptr;
4216 // Couldn't match.
4217 TPT.rollback(LastKnownGood);
4218 return false;
4221 /// Check to see if all uses of OpVal by the specified inline asm call are due
4222 /// to memory operands. If so, return true, otherwise return false.
4223 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
4224 const TargetLowering &TLI,
4225 const TargetRegisterInfo &TRI) {
4226 const Function *F = CI->getFunction();
4227 TargetLowering::AsmOperandInfoVector TargetConstraints =
4228 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
4229 ImmutableCallSite(CI));
4231 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4232 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4234 // Compute the constraint code and ConstraintType to use.
4235 TLI.ComputeConstraintToUse(OpInfo, SDValue());
4237 // If this asm operand is our Value*, and if it isn't an indirect memory
4238 // operand, we can't fold it!
4239 if (OpInfo.CallOperandVal == OpVal &&
4240 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4241 !OpInfo.isIndirect))
4242 return false;
4245 return true;
4248 // Max number of memory uses to look at before aborting the search to conserve
4249 // compile time.
4250 static constexpr int MaxMemoryUsesToScan = 20;
4252 /// Recursively walk all the uses of I until we find a memory use.
4253 /// If we find an obviously non-foldable instruction, return true.
4254 /// Add the ultimately found memory instructions to MemoryUses.
4255 static bool FindAllMemoryUses(
4256 Instruction *I,
4257 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
4258 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4259 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
4260 // If we already considered this instruction, we're done.
4261 if (!ConsideredInsts.insert(I).second)
4262 return false;
4264 // If this is an obviously unfoldable instruction, bail out.
4265 if (!MightBeFoldableInst(I))
4266 return true;
4268 const bool OptSize = I->getFunction()->optForSize();
4270 // Loop over all the uses, recursively processing them.
4271 for (Use &U : I->uses()) {
4272 // Conservatively return true if we're seeing a large number or a deep chain
4273 // of users. This avoids excessive compilation times in pathological cases.
4274 if (SeenInsts++ >= MaxMemoryUsesToScan)
4275 return true;
4277 Instruction *UserI = cast<Instruction>(U.getUser());
4278 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4279 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4280 continue;
4283 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4284 unsigned opNo = U.getOperandNo();
4285 if (opNo != StoreInst::getPointerOperandIndex())
4286 return true; // Storing addr, not into addr.
4287 MemoryUses.push_back(std::make_pair(SI, opNo));
4288 continue;
4291 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4292 unsigned opNo = U.getOperandNo();
4293 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4294 return true; // Storing addr, not into addr.
4295 MemoryUses.push_back(std::make_pair(RMW, opNo));
4296 continue;
4299 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4300 unsigned opNo = U.getOperandNo();
4301 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4302 return true; // Storing addr, not into addr.
4303 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4304 continue;
4307 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
4308 // If this is a cold call, we can sink the addressing calculation into
4309 // the cold path. See optimizeCallInst
4310 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4311 continue;
4313 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4314 if (!IA) return true;
4316 // If this is a memory operand, we're cool, otherwise bail out.
4317 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
4318 return true;
4319 continue;
4322 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4323 SeenInsts))
4324 return true;
4327 return false;
4330 /// Return true if Val is already known to be live at the use site that we're
4331 /// folding it into. If so, there is no cost to include it in the addressing
4332 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4333 /// instruction already.
4334 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4335 Value *KnownLive2) {
4336 // If Val is either of the known-live values, we know it is live!
4337 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4338 return true;
4340 // All values other than instructions and arguments (e.g. constants) are live.
4341 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4343 // If Val is a constant sized alloca in the entry block, it is live, this is
4344 // true because it is just a reference to the stack/frame pointer, which is
4345 // live for the whole function.
4346 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4347 if (AI->isStaticAlloca())
4348 return true;
4350 // Check to see if this value is already used in the memory instruction's
4351 // block. If so, it's already live into the block at the very least, so we
4352 // can reasonably fold it.
4353 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4356 /// It is possible for the addressing mode of the machine to fold the specified
4357 /// instruction into a load or store that ultimately uses it.
4358 /// However, the specified instruction has multiple uses.
4359 /// Given this, it may actually increase register pressure to fold it
4360 /// into the load. For example, consider this code:
4362 /// X = ...
4363 /// Y = X+1
4364 /// use(Y) -> nonload/store
4365 /// Z = Y+1
4366 /// load Z
4368 /// In this case, Y has multiple uses, and can be folded into the load of Z
4369 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4370 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4371 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4372 /// number of computations either.
4374 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4375 /// X was live across 'load Z' for other reasons, we actually *would* want to
4376 /// fold the addressing mode in the Z case. This would make Y die earlier.
4377 bool AddressingModeMatcher::
4378 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4379 ExtAddrMode &AMAfter) {
4380 if (IgnoreProfitability) return true;
4382 // AMBefore is the addressing mode before this instruction was folded into it,
4383 // and AMAfter is the addressing mode after the instruction was folded. Get
4384 // the set of registers referenced by AMAfter and subtract out those
4385 // referenced by AMBefore: this is the set of values which folding in this
4386 // address extends the lifetime of.
4388 // Note that there are only two potential values being referenced here,
4389 // BaseReg and ScaleReg (global addresses are always available, as are any
4390 // folded immediates).
4391 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4393 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4394 // lifetime wasn't extended by adding this instruction.
4395 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4396 BaseReg = nullptr;
4397 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4398 ScaledReg = nullptr;
4400 // If folding this instruction (and it's subexprs) didn't extend any live
4401 // ranges, we're ok with it.
4402 if (!BaseReg && !ScaledReg)
4403 return true;
4405 // If all uses of this instruction can have the address mode sunk into them,
4406 // we can remove the addressing mode and effectively trade one live register
4407 // for another (at worst.) In this context, folding an addressing mode into
4408 // the use is just a particularly nice way of sinking it.
4409 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4410 SmallPtrSet<Instruction*, 16> ConsideredInsts;
4411 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
4412 return false; // Has a non-memory, non-foldable use!
4414 // Now that we know that all uses of this instruction are part of a chain of
4415 // computation involving only operations that could theoretically be folded
4416 // into a memory use, loop over each of these memory operation uses and see
4417 // if they could *actually* fold the instruction. The assumption is that
4418 // addressing modes are cheap and that duplicating the computation involved
4419 // many times is worthwhile, even on a fastpath. For sinking candidates
4420 // (i.e. cold call sites), this serves as a way to prevent excessive code
4421 // growth since most architectures have some reasonable small and fast way to
4422 // compute an effective address. (i.e LEA on x86)
4423 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4424 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4425 Instruction *User = MemoryUses[i].first;
4426 unsigned OpNo = MemoryUses[i].second;
4428 // Get the access type of this use. If the use isn't a pointer, we don't
4429 // know what it accesses.
4430 Value *Address = User->getOperand(OpNo);
4431 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4432 if (!AddrTy)
4433 return false;
4434 Type *AddressAccessTy = AddrTy->getElementType();
4435 unsigned AS = AddrTy->getAddressSpace();
4437 // Do a match against the root of this address, ignoring profitability. This
4438 // will tell us if the addressing mode for the memory operation will
4439 // *actually* cover the shared instruction.
4440 ExtAddrMode Result;
4441 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4443 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4444 TPT.getRestorationPoint();
4445 AddressingModeMatcher Matcher(
4446 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4447 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
4448 Matcher.IgnoreProfitability = true;
4449 bool Success = Matcher.matchAddr(Address, 0);
4450 (void)Success; assert(Success && "Couldn't select *anything*?");
4452 // The match was to check the profitability, the changes made are not
4453 // part of the original matcher. Therefore, they should be dropped
4454 // otherwise the original matcher will not present the right state.
4455 TPT.rollback(LastKnownGood);
4457 // If the match didn't cover I, then it won't be shared by it.
4458 if (!is_contained(MatchedAddrModeInsts, I))
4459 return false;
4461 MatchedAddrModeInsts.clear();
4464 return true;
4467 /// Return true if the specified values are defined in a
4468 /// different basic block than BB.
4469 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4470 if (Instruction *I = dyn_cast<Instruction>(V))
4471 return I->getParent() != BB;
4472 return false;
4475 /// Sink addressing mode computation immediate before MemoryInst if doing so
4476 /// can be done without increasing register pressure. The need for the
4477 /// register pressure constraint means this can end up being an all or nothing
4478 /// decision for all uses of the same addressing computation.
4480 /// Load and Store Instructions often have addressing modes that can do
4481 /// significant amounts of computation. As such, instruction selection will try
4482 /// to get the load or store to do as much computation as possible for the
4483 /// program. The problem is that isel can only see within a single block. As
4484 /// such, we sink as much legal addressing mode work into the block as possible.
4486 /// This method is used to optimize both load/store and inline asms with memory
4487 /// operands. It's also used to sink addressing computations feeding into cold
4488 /// call sites into their (cold) basic block.
4490 /// The motivation for handling sinking into cold blocks is that doing so can
4491 /// both enable other address mode sinking (by satisfying the register pressure
4492 /// constraint above), and reduce register pressure globally (by removing the
4493 /// addressing mode computation from the fast path entirely.).
4494 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
4495 Type *AccessTy, unsigned AddrSpace) {
4496 Value *Repl = Addr;
4498 // Try to collapse single-value PHI nodes. This is necessary to undo
4499 // unprofitable PRE transformations.
4500 SmallVector<Value*, 8> worklist;
4501 SmallPtrSet<Value*, 16> Visited;
4502 worklist.push_back(Addr);
4504 // Use a worklist to iteratively look through PHI and select nodes, and
4505 // ensure that the addressing mode obtained from the non-PHI/select roots of
4506 // the graph are compatible.
4507 bool PhiOrSelectSeen = false;
4508 SmallVector<Instruction*, 16> AddrModeInsts;
4509 const SimplifyQuery SQ(*DL, TLInfo);
4510 AddressingModeCombiner AddrModes(SQ, Addr);
4511 TypePromotionTransaction TPT(RemovedInsts);
4512 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4513 TPT.getRestorationPoint();
4514 while (!worklist.empty()) {
4515 Value *V = worklist.back();
4516 worklist.pop_back();
4518 // We allow traversing cyclic Phi nodes.
4519 // In case of success after this loop we ensure that traversing through
4520 // Phi nodes ends up with all cases to compute address of the form
4521 // BaseGV + Base + Scale * Index + Offset
4522 // where Scale and Offset are constans and BaseGV, Base and Index
4523 // are exactly the same Values in all cases.
4524 // It means that BaseGV, Scale and Offset dominate our memory instruction
4525 // and have the same value as they had in address computation represented
4526 // as Phi. So we can safely sink address computation to memory instruction.
4527 if (!Visited.insert(V).second)
4528 continue;
4530 // For a PHI node, push all of its incoming values.
4531 if (PHINode *P = dyn_cast<PHINode>(V)) {
4532 for (Value *IncValue : P->incoming_values())
4533 worklist.push_back(IncValue);
4534 PhiOrSelectSeen = true;
4535 continue;
4537 // Similar for select.
4538 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4539 worklist.push_back(SI->getFalseValue());
4540 worklist.push_back(SI->getTrueValue());
4541 PhiOrSelectSeen = true;
4542 continue;
4545 // For non-PHIs, determine the addressing mode being computed. Note that
4546 // the result may differ depending on what other uses our candidate
4547 // addressing instructions might have.
4548 AddrModeInsts.clear();
4549 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4551 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4552 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4553 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
4555 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4556 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4557 !NewGEPBases.count(GEP)) {
4558 // If splitting the underlying data structure can reduce the offset of a
4559 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4560 // previously split data structures.
4561 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4562 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4563 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4566 NewAddrMode.OriginalValue = V;
4567 if (!AddrModes.addNewAddrMode(NewAddrMode))
4568 break;
4571 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4572 // or we have multiple but either couldn't combine them or combining them
4573 // wouldn't do anything useful, bail out now.
4574 if (!AddrModes.combineAddrModes()) {
4575 TPT.rollback(LastKnownGood);
4576 return false;
4578 TPT.commit();
4580 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4581 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4583 // If all the instructions matched are already in this BB, don't do anything.
4584 // If we saw a Phi node then it is not local definitely, and if we saw a select
4585 // then we want to push the address calculation past it even if it's already
4586 // in this BB.
4587 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
4588 return IsNonLocalValue(V, MemoryInst->getParent());
4589 })) {
4590 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4591 << "\n");
4592 return false;
4595 // Insert this computation right after this user. Since our caller is
4596 // scanning from the top of the BB to the bottom, reuse of the expr are
4597 // guaranteed to happen later.
4598 IRBuilder<> Builder(MemoryInst);
4600 // Now that we determined the addressing expression we want to use and know
4601 // that we have to sink it into this block. Check to see if we have already
4602 // done this for some other load/store instr in this block. If so, reuse
4603 // the computation. Before attempting reuse, check if the address is valid
4604 // as it may have been erased.
4606 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4608 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
4609 if (SunkAddr) {
4610 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4611 << " for " << *MemoryInst << "\n");
4612 if (SunkAddr->getType() != Addr->getType())
4613 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4614 } else if (AddrSinkUsingGEPs ||
4615 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
4616 // By default, we use the GEP-based method when AA is used later. This
4617 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4618 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4619 << " for " << *MemoryInst << "\n");
4620 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4621 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
4623 // First, find the pointer.
4624 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4625 ResultPtr = AddrMode.BaseReg;
4626 AddrMode.BaseReg = nullptr;
4629 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4630 // We can't add more than one pointer together, nor can we scale a
4631 // pointer (both of which seem meaningless).
4632 if (ResultPtr || AddrMode.Scale != 1)
4633 return false;
4635 ResultPtr = AddrMode.ScaledReg;
4636 AddrMode.Scale = 0;
4639 // It is only safe to sign extend the BaseReg if we know that the math
4640 // required to create it did not overflow before we extend it. Since
4641 // the original IR value was tossed in favor of a constant back when
4642 // the AddrMode was created we need to bail out gracefully if widths
4643 // do not match instead of extending it.
4645 // (See below for code to add the scale.)
4646 if (AddrMode.Scale) {
4647 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4648 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4649 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4650 return false;
4653 if (AddrMode.BaseGV) {
4654 if (ResultPtr)
4655 return false;
4657 ResultPtr = AddrMode.BaseGV;
4660 // If the real base value actually came from an inttoptr, then the matcher
4661 // will look through it and provide only the integer value. In that case,
4662 // use it here.
4663 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4664 const auto getResultPtr = [MemoryInst, Addr,
4665 &Builder](Value *Reg) -> Value * {
4666 BasicBlock *BB = MemoryInst->getParent();
4667 for (User *U : Reg->users())
4668 if (auto *I2P = dyn_cast<IntToPtrInst>(U))
4669 if (I2P->getType() == Addr->getType() && I2P->getParent() == BB) {
4670 auto *RegInst = dyn_cast<Instruction>(Reg);
4671 if (RegInst && RegInst->getParent() == BB &&
4672 !isa<PHINode>(RegInst) && !RegInst->isEHPad())
4673 I2P->moveAfter(RegInst);
4674 else
4675 I2P->moveBefore(*BB, BB->getFirstInsertionPt());
4676 return I2P;
4678 return Builder.CreateIntToPtr(Reg, Addr->getType(), "sunkaddr");
4680 if (!ResultPtr && AddrMode.BaseReg) {
4681 ResultPtr = getResultPtr(AddrMode.BaseReg);
4682 AddrMode.BaseReg = nullptr;
4683 } else if (!ResultPtr && AddrMode.Scale == 1) {
4684 ResultPtr = getResultPtr(AddrMode.ScaledReg);
4685 AddrMode.Scale = 0;
4689 if (!ResultPtr &&
4690 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4691 SunkAddr = Constant::getNullValue(Addr->getType());
4692 } else if (!ResultPtr) {
4693 return false;
4694 } else {
4695 Type *I8PtrTy =
4696 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4697 Type *I8Ty = Builder.getInt8Ty();
4699 // Start with the base register. Do this first so that subsequent address
4700 // matching finds it last, which will prevent it from trying to match it
4701 // as the scaled value in case it happens to be a mul. That would be
4702 // problematic if we've sunk a different mul for the scale, because then
4703 // we'd end up sinking both muls.
4704 if (AddrMode.BaseReg) {
4705 Value *V = AddrMode.BaseReg;
4706 if (V->getType() != IntPtrTy)
4707 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4709 ResultIndex = V;
4712 // Add the scale value.
4713 if (AddrMode.Scale) {
4714 Value *V = AddrMode.ScaledReg;
4715 if (V->getType() == IntPtrTy) {
4716 // done.
4717 } else {
4718 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4719 cast<IntegerType>(V->getType())->getBitWidth() &&
4720 "We can't transform if ScaledReg is too narrow");
4721 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4724 if (AddrMode.Scale != 1)
4725 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4726 "sunkaddr");
4727 if (ResultIndex)
4728 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4729 else
4730 ResultIndex = V;
4733 // Add in the Base Offset if present.
4734 if (AddrMode.BaseOffs) {
4735 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4736 if (ResultIndex) {
4737 // We need to add this separately from the scale above to help with
4738 // SDAG consecutive load/store merging.
4739 if (ResultPtr->getType() != I8PtrTy)
4740 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4741 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4744 ResultIndex = V;
4747 if (!ResultIndex) {
4748 SunkAddr = ResultPtr;
4749 } else {
4750 if (ResultPtr->getType() != I8PtrTy)
4751 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4752 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4755 if (SunkAddr->getType() != Addr->getType())
4756 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4758 } else {
4759 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4760 // non-integral pointers, so in that case bail out now.
4761 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4762 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4763 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4764 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4765 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4766 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4767 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4768 (AddrMode.BaseGV &&
4769 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4770 return false;
4772 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4773 << " for " << *MemoryInst << "\n");
4774 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4775 Value *Result = nullptr;
4777 // Start with the base register. Do this first so that subsequent address
4778 // matching finds it last, which will prevent it from trying to match it
4779 // as the scaled value in case it happens to be a mul. That would be
4780 // problematic if we've sunk a different mul for the scale, because then
4781 // we'd end up sinking both muls.
4782 if (AddrMode.BaseReg) {
4783 Value *V = AddrMode.BaseReg;
4784 if (V->getType()->isPointerTy())
4785 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4786 if (V->getType() != IntPtrTy)
4787 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4788 Result = V;
4791 // Add the scale value.
4792 if (AddrMode.Scale) {
4793 Value *V = AddrMode.ScaledReg;
4794 if (V->getType() == IntPtrTy) {
4795 // done.
4796 } else if (V->getType()->isPointerTy()) {
4797 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4798 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4799 cast<IntegerType>(V->getType())->getBitWidth()) {
4800 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4801 } else {
4802 // It is only safe to sign extend the BaseReg if we know that the math
4803 // required to create it did not overflow before we extend it. Since
4804 // the original IR value was tossed in favor of a constant back when
4805 // the AddrMode was created we need to bail out gracefully if widths
4806 // do not match instead of extending it.
4807 Instruction *I = dyn_cast_or_null<Instruction>(Result);
4808 if (I && (Result != AddrMode.BaseReg))
4809 I->eraseFromParent();
4810 return false;
4812 if (AddrMode.Scale != 1)
4813 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4814 "sunkaddr");
4815 if (Result)
4816 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4817 else
4818 Result = V;
4821 // Add in the BaseGV if present.
4822 if (AddrMode.BaseGV) {
4823 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
4824 if (Result)
4825 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4826 else
4827 Result = V;
4830 // Add in the Base Offset if present.
4831 if (AddrMode.BaseOffs) {
4832 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4833 if (Result)
4834 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4835 else
4836 Result = V;
4839 if (!Result)
4840 SunkAddr = Constant::getNullValue(Addr->getType());
4841 else
4842 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
4845 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
4846 // Store the newly computed address into the cache. In the case we reused a
4847 // value, this should be idempotent.
4848 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
4850 // If we have no uses, recursively delete the value and all dead instructions
4851 // using it.
4852 if (Repl->use_empty()) {
4853 // This can cause recursive deletion, which can invalidate our iterator.
4854 // Use a WeakTrackingVH to hold onto it in case this happens.
4855 Value *CurValue = &*CurInstIterator;
4856 WeakTrackingVH IterHandle(CurValue);
4857 BasicBlock *BB = CurInstIterator->getParent();
4859 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
4861 if (IterHandle != CurValue) {
4862 // If the iterator instruction was recursively deleted, start over at the
4863 // start of the block.
4864 CurInstIterator = BB->begin();
4865 SunkAddrs.clear();
4868 ++NumMemoryInsts;
4869 return true;
4872 /// If there are any memory operands, use OptimizeMemoryInst to sink their
4873 /// address computing into the block when possible / profitable.
4874 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
4875 bool MadeChange = false;
4877 const TargetRegisterInfo *TRI =
4878 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
4879 TargetLowering::AsmOperandInfoVector TargetConstraints =
4880 TLI->ParseConstraints(*DL, TRI, CS);
4881 unsigned ArgNo = 0;
4882 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4883 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4885 // Compute the constraint code and ConstraintType to use.
4886 TLI->ComputeConstraintToUse(OpInfo, SDValue());
4888 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4889 OpInfo.isIndirect) {
4890 Value *OpVal = CS->getArgOperand(ArgNo++);
4891 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
4892 } else if (OpInfo.Type == InlineAsm::isInput)
4893 ArgNo++;
4896 return MadeChange;
4899 /// Check if all the uses of \p Val are equivalent (or free) zero or
4900 /// sign extensions.
4901 static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4902 assert(!Val->use_empty() && "Input must have at least one use");
4903 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
4904 bool IsSExt = isa<SExtInst>(FirstUser);
4905 Type *ExtTy = FirstUser->getType();
4906 for (const User *U : Val->users()) {
4907 const Instruction *UI = cast<Instruction>(U);
4908 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4909 return false;
4910 Type *CurTy = UI->getType();
4911 // Same input and output types: Same instruction after CSE.
4912 if (CurTy == ExtTy)
4913 continue;
4915 // If IsSExt is true, we are in this situation:
4916 // a = Val
4917 // b = sext ty1 a to ty2
4918 // c = sext ty1 a to ty3
4919 // Assuming ty2 is shorter than ty3, this could be turned into:
4920 // a = Val
4921 // b = sext ty1 a to ty2
4922 // c = sext ty2 b to ty3
4923 // However, the last sext is not free.
4924 if (IsSExt)
4925 return false;
4927 // This is a ZExt, maybe this is free to extend from one type to another.
4928 // In that case, we would not account for a different use.
4929 Type *NarrowTy;
4930 Type *LargeTy;
4931 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4932 CurTy->getScalarType()->getIntegerBitWidth()) {
4933 NarrowTy = CurTy;
4934 LargeTy = ExtTy;
4935 } else {
4936 NarrowTy = ExtTy;
4937 LargeTy = CurTy;
4940 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4941 return false;
4943 // All uses are the same or can be derived from one another for free.
4944 return true;
4947 /// Try to speculatively promote extensions in \p Exts and continue
4948 /// promoting through newly promoted operands recursively as far as doing so is
4949 /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4950 /// When some promotion happened, \p TPT contains the proper state to revert
4951 /// them.
4953 /// \return true if some promotion happened, false otherwise.
4954 bool CodeGenPrepare::tryToPromoteExts(
4955 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4956 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4957 unsigned CreatedInstsCost) {
4958 bool Promoted = false;
4960 // Iterate over all the extensions to try to promote them.
4961 for (auto I : Exts) {
4962 // Early check if we directly have ext(load).
4963 if (isa<LoadInst>(I->getOperand(0))) {
4964 ProfitablyMovedExts.push_back(I);
4965 continue;
4968 // Check whether or not we want to do any promotion. The reason we have
4969 // this check inside the for loop is to catch the case where an extension
4970 // is directly fed by a load because in such case the extension can be moved
4971 // up without any promotion on its operands.
4972 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4973 return false;
4975 // Get the action to perform the promotion.
4976 TypePromotionHelper::Action TPH =
4977 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
4978 // Check if we can promote.
4979 if (!TPH) {
4980 // Save the current extension as we cannot move up through its operand.
4981 ProfitablyMovedExts.push_back(I);
4982 continue;
4985 // Save the current state.
4986 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4987 TPT.getRestorationPoint();
4988 SmallVector<Instruction *, 4> NewExts;
4989 unsigned NewCreatedInstsCost = 0;
4990 unsigned ExtCost = !TLI->isExtFree(I);
4991 // Promote.
4992 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4993 &NewExts, nullptr, *TLI);
4994 assert(PromotedVal &&
4995 "TypePromotionHelper should have filtered out those cases");
4997 // We would be able to merge only one extension in a load.
4998 // Therefore, if we have more than 1 new extension we heuristically
4999 // cut this search path, because it means we degrade the code quality.
5000 // With exactly 2, the transformation is neutral, because we will merge
5001 // one extension but leave one. However, we optimistically keep going,
5002 // because the new extension may be removed too.
5003 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
5004 // FIXME: It would be possible to propagate a negative value instead of
5005 // conservatively ceiling it to 0.
5006 TotalCreatedInstsCost =
5007 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
5008 if (!StressExtLdPromotion &&
5009 (TotalCreatedInstsCost > 1 ||
5010 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
5011 // This promotion is not profitable, rollback to the previous state, and
5012 // save the current extension in ProfitablyMovedExts as the latest
5013 // speculative promotion turned out to be unprofitable.
5014 TPT.rollback(LastKnownGood);
5015 ProfitablyMovedExts.push_back(I);
5016 continue;
5018 // Continue promoting NewExts as far as doing so is profitable.
5019 SmallVector<Instruction *, 2> NewlyMovedExts;
5020 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5021 bool NewPromoted = false;
5022 for (auto ExtInst : NewlyMovedExts) {
5023 Instruction *MovedExt = cast<Instruction>(ExtInst);
5024 Value *ExtOperand = MovedExt->getOperand(0);
5025 // If we have reached to a load, we need this extra profitability check
5026 // as it could potentially be merged into an ext(load).
5027 if (isa<LoadInst>(ExtOperand) &&
5028 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5029 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5030 continue;
5032 ProfitablyMovedExts.push_back(MovedExt);
5033 NewPromoted = true;
5036 // If none of speculative promotions for NewExts is profitable, rollback
5037 // and save the current extension (I) as the last profitable extension.
5038 if (!NewPromoted) {
5039 TPT.rollback(LastKnownGood);
5040 ProfitablyMovedExts.push_back(I);
5041 continue;
5043 // The promotion is profitable.
5044 Promoted = true;
5046 return Promoted;
5049 /// Merging redundant sexts when one is dominating the other.
5050 bool CodeGenPrepare::mergeSExts(Function &F) {
5051 DominatorTree DT(F);
5052 bool Changed = false;
5053 for (auto &Entry : ValToSExtendedUses) {
5054 SExts &Insts = Entry.second;
5055 SExts CurPts;
5056 for (Instruction *Inst : Insts) {
5057 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5058 Inst->getOperand(0) != Entry.first)
5059 continue;
5060 bool inserted = false;
5061 for (auto &Pt : CurPts) {
5062 if (DT.dominates(Inst, Pt)) {
5063 Pt->replaceAllUsesWith(Inst);
5064 RemovedInsts.insert(Pt);
5065 Pt->removeFromParent();
5066 Pt = Inst;
5067 inserted = true;
5068 Changed = true;
5069 break;
5071 if (!DT.dominates(Pt, Inst))
5072 // Give up if we need to merge in a common dominator as the
5073 // experiments show it is not profitable.
5074 continue;
5075 Inst->replaceAllUsesWith(Pt);
5076 RemovedInsts.insert(Inst);
5077 Inst->removeFromParent();
5078 inserted = true;
5079 Changed = true;
5080 break;
5082 if (!inserted)
5083 CurPts.push_back(Inst);
5086 return Changed;
5089 // Spliting large data structures so that the GEPs accessing them can have
5090 // smaller offsets so that they can be sunk to the same blocks as their users.
5091 // For example, a large struct starting from %base is splitted into two parts
5092 // where the second part starts from %new_base.
5094 // Before:
5095 // BB0:
5096 // %base =
5098 // BB1:
5099 // %gep0 = gep %base, off0
5100 // %gep1 = gep %base, off1
5101 // %gep2 = gep %base, off2
5103 // BB2:
5104 // %load1 = load %gep0
5105 // %load2 = load %gep1
5106 // %load3 = load %gep2
5108 // After:
5109 // BB0:
5110 // %base =
5111 // %new_base = gep %base, off0
5113 // BB1:
5114 // %new_gep0 = %new_base
5115 // %new_gep1 = gep %new_base, off1 - off0
5116 // %new_gep2 = gep %new_base, off2 - off0
5118 // BB2:
5119 // %load1 = load i32, i32* %new_gep0
5120 // %load2 = load i32, i32* %new_gep1
5121 // %load3 = load i32, i32* %new_gep2
5123 // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
5124 // their offsets are smaller enough to fit into the addressing mode.
5125 bool CodeGenPrepare::splitLargeGEPOffsets() {
5126 bool Changed = false;
5127 for (auto &Entry : LargeOffsetGEPMap) {
5128 Value *OldBase = Entry.first;
5129 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
5130 &LargeOffsetGEPs = Entry.second;
5131 auto compareGEPOffset =
5132 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
5133 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
5134 if (LHS.first == RHS.first)
5135 return false;
5136 if (LHS.second != RHS.second)
5137 return LHS.second < RHS.second;
5138 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
5140 // Sorting all the GEPs of the same data structures based on the offsets.
5141 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
5142 LargeOffsetGEPs.erase(
5143 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
5144 LargeOffsetGEPs.end());
5145 // Skip if all the GEPs have the same offsets.
5146 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
5147 continue;
5148 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
5149 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
5150 Value *NewBaseGEP = nullptr;
5152 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
5153 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
5154 GetElementPtrInst *GEP = LargeOffsetGEP->first;
5155 int64_t Offset = LargeOffsetGEP->second;
5156 if (Offset != BaseOffset) {
5157 TargetLowering::AddrMode AddrMode;
5158 AddrMode.BaseOffs = Offset - BaseOffset;
5159 // The result type of the GEP might not be the type of the memory
5160 // access.
5161 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
5162 GEP->getResultElementType(),
5163 GEP->getAddressSpace())) {
5164 // We need to create a new base if the offset to the current base is
5165 // too large to fit into the addressing mode. So, a very large struct
5166 // may be splitted into several parts.
5167 BaseGEP = GEP;
5168 BaseOffset = Offset;
5169 NewBaseGEP = nullptr;
5173 // Generate a new GEP to replace the current one.
5174 LLVMContext &Ctx = GEP->getContext();
5175 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
5176 Type *I8PtrTy =
5177 Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
5178 Type *I8Ty = Type::getInt8Ty(Ctx);
5180 if (!NewBaseGEP) {
5181 // Create a new base if we don't have one yet. Find the insertion
5182 // pointer for the new base first.
5183 BasicBlock::iterator NewBaseInsertPt;
5184 BasicBlock *NewBaseInsertBB;
5185 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5186 // If the base of the struct is an instruction, the new base will be
5187 // inserted close to it.
5188 NewBaseInsertBB = BaseI->getParent();
5189 if (isa<PHINode>(BaseI))
5190 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5191 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5192 NewBaseInsertBB =
5193 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5194 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5195 } else
5196 NewBaseInsertPt = std::next(BaseI->getIterator());
5197 } else {
5198 // If the current base is an argument or global value, the new base
5199 // will be inserted to the entry block.
5200 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5201 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5203 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5204 // Create a new base.
5205 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5206 NewBaseGEP = OldBase;
5207 if (NewBaseGEP->getType() != I8PtrTy)
5208 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5209 NewBaseGEP =
5210 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5211 NewGEPBases.insert(NewBaseGEP);
5214 IRBuilder<> Builder(GEP);
5215 Value *NewGEP = NewBaseGEP;
5216 if (Offset == BaseOffset) {
5217 if (GEP->getType() != I8PtrTy)
5218 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5219 } else {
5220 // Calculate the new offset for the new GEP.
5221 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5222 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5224 if (GEP->getType() != I8PtrTy)
5225 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5227 GEP->replaceAllUsesWith(NewGEP);
5228 LargeOffsetGEPID.erase(GEP);
5229 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5230 GEP->eraseFromParent();
5231 Changed = true;
5234 return Changed;
5237 /// Return true, if an ext(load) can be formed from an extension in
5238 /// \p MovedExts.
5239 bool CodeGenPrepare::canFormExtLd(
5240 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5241 Instruction *&Inst, bool HasPromoted) {
5242 for (auto *MovedExtInst : MovedExts) {
5243 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5244 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5245 Inst = MovedExtInst;
5246 break;
5249 if (!LI)
5250 return false;
5252 // If they're already in the same block, there's nothing to do.
5253 // Make the cheap checks first if we did not promote.
5254 // If we promoted, we need to check if it is indeed profitable.
5255 if (!HasPromoted && LI->getParent() == Inst->getParent())
5256 return false;
5258 return TLI->isExtLoad(LI, Inst, *DL);
5261 /// Move a zext or sext fed by a load into the same basic block as the load,
5262 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
5263 /// extend into the load.
5265 /// E.g.,
5266 /// \code
5267 /// %ld = load i32* %addr
5268 /// %add = add nuw i32 %ld, 4
5269 /// %zext = zext i32 %add to i64
5270 // \endcode
5271 /// =>
5272 /// \code
5273 /// %ld = load i32* %addr
5274 /// %zext = zext i32 %ld to i64
5275 /// %add = add nuw i64 %zext, 4
5276 /// \encode
5277 /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5278 /// allow us to match zext(load i32*) to i64.
5280 /// Also, try to promote the computations used to obtain a sign extended
5281 /// value used into memory accesses.
5282 /// E.g.,
5283 /// \code
5284 /// a = add nsw i32 b, 3
5285 /// d = sext i32 a to i64
5286 /// e = getelementptr ..., i64 d
5287 /// \endcode
5288 /// =>
5289 /// \code
5290 /// f = sext i32 b to i64
5291 /// a = add nsw i64 f, 3
5292 /// e = getelementptr ..., i64 a
5293 /// \endcode
5295 /// \p Inst[in/out] the extension may be modified during the process if some
5296 /// promotions apply.
5297 bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5298 // ExtLoad formation and address type promotion infrastructure requires TLI to
5299 // be effective.
5300 if (!TLI)
5301 return false;
5303 bool AllowPromotionWithoutCommonHeader = false;
5304 /// See if it is an interesting sext operations for the address type
5305 /// promotion before trying to promote it, e.g., the ones with the right
5306 /// type and used in memory accesses.
5307 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5308 *Inst, AllowPromotionWithoutCommonHeader);
5309 TypePromotionTransaction TPT(RemovedInsts);
5310 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5311 TPT.getRestorationPoint();
5312 SmallVector<Instruction *, 1> Exts;
5313 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5314 Exts.push_back(Inst);
5316 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
5318 // Look for a load being extended.
5319 LoadInst *LI = nullptr;
5320 Instruction *ExtFedByLoad;
5322 // Try to promote a chain of computation if it allows to form an extended
5323 // load.
5324 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5325 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5326 TPT.commit();
5327 // Move the extend into the same block as the load
5328 ExtFedByLoad->moveAfter(LI);
5329 // CGP does not check if the zext would be speculatively executed when moved
5330 // to the same basic block as the load. Preserving its original location
5331 // would pessimize the debugging experience, as well as negatively impact
5332 // the quality of sample pgo. We don't want to use "line 0" as that has a
5333 // size cost in the line-table section and logically the zext can be seen as
5334 // part of the load. Therefore we conservatively reuse the same debug
5335 // location for the load and the zext.
5336 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5337 ++NumExtsMoved;
5338 Inst = ExtFedByLoad;
5339 return true;
5342 // Continue promoting SExts if known as considerable depending on targets.
5343 if (ATPConsiderable &&
5344 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5345 HasPromoted, TPT, SpeculativelyMovedExts))
5346 return true;
5348 TPT.rollback(LastKnownGood);
5349 return false;
5352 // Perform address type promotion if doing so is profitable.
5353 // If AllowPromotionWithoutCommonHeader == false, we should find other sext
5354 // instructions that sign extended the same initial value. However, if
5355 // AllowPromotionWithoutCommonHeader == true, we expect promoting the
5356 // extension is just profitable.
5357 bool CodeGenPrepare::performAddressTypePromotion(
5358 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5359 bool HasPromoted, TypePromotionTransaction &TPT,
5360 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5361 bool Promoted = false;
5362 SmallPtrSet<Instruction *, 1> UnhandledExts;
5363 bool AllSeenFirst = true;
5364 for (auto I : SpeculativelyMovedExts) {
5365 Value *HeadOfChain = I->getOperand(0);
5366 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5367 SeenChainsForSExt.find(HeadOfChain);
5368 // If there is an unhandled SExt which has the same header, try to promote
5369 // it as well.
5370 if (AlreadySeen != SeenChainsForSExt.end()) {
5371 if (AlreadySeen->second != nullptr)
5372 UnhandledExts.insert(AlreadySeen->second);
5373 AllSeenFirst = false;
5377 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5378 SpeculativelyMovedExts.size() == 1)) {
5379 TPT.commit();
5380 if (HasPromoted)
5381 Promoted = true;
5382 for (auto I : SpeculativelyMovedExts) {
5383 Value *HeadOfChain = I->getOperand(0);
5384 SeenChainsForSExt[HeadOfChain] = nullptr;
5385 ValToSExtendedUses[HeadOfChain].push_back(I);
5387 // Update Inst as promotion happen.
5388 Inst = SpeculativelyMovedExts.pop_back_val();
5389 } else {
5390 // This is the first chain visited from the header, keep the current chain
5391 // as unhandled. Defer to promote this until we encounter another SExt
5392 // chain derived from the same header.
5393 for (auto I : SpeculativelyMovedExts) {
5394 Value *HeadOfChain = I->getOperand(0);
5395 SeenChainsForSExt[HeadOfChain] = Inst;
5397 return false;
5400 if (!AllSeenFirst && !UnhandledExts.empty())
5401 for (auto VisitedSExt : UnhandledExts) {
5402 if (RemovedInsts.count(VisitedSExt))
5403 continue;
5404 TypePromotionTransaction TPT(RemovedInsts);
5405 SmallVector<Instruction *, 1> Exts;
5406 SmallVector<Instruction *, 2> Chains;
5407 Exts.push_back(VisitedSExt);
5408 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5409 TPT.commit();
5410 if (HasPromoted)
5411 Promoted = true;
5412 for (auto I : Chains) {
5413 Value *HeadOfChain = I->getOperand(0);
5414 // Mark this as handled.
5415 SeenChainsForSExt[HeadOfChain] = nullptr;
5416 ValToSExtendedUses[HeadOfChain].push_back(I);
5419 return Promoted;
5422 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
5423 BasicBlock *DefBB = I->getParent();
5425 // If the result of a {s|z}ext and its source are both live out, rewrite all
5426 // other uses of the source with result of extension.
5427 Value *Src = I->getOperand(0);
5428 if (Src->hasOneUse())
5429 return false;
5431 // Only do this xform if truncating is free.
5432 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
5433 return false;
5435 // Only safe to perform the optimization if the source is also defined in
5436 // this block.
5437 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
5438 return false;
5440 bool DefIsLiveOut = false;
5441 for (User *U : I->users()) {
5442 Instruction *UI = cast<Instruction>(U);
5444 // Figure out which BB this ext is used in.
5445 BasicBlock *UserBB = UI->getParent();
5446 if (UserBB == DefBB) continue;
5447 DefIsLiveOut = true;
5448 break;
5450 if (!DefIsLiveOut)
5451 return false;
5453 // Make sure none of the uses are PHI nodes.
5454 for (User *U : Src->users()) {
5455 Instruction *UI = cast<Instruction>(U);
5456 BasicBlock *UserBB = UI->getParent();
5457 if (UserBB == DefBB) continue;
5458 // Be conservative. We don't want this xform to end up introducing
5459 // reloads just before load / store instructions.
5460 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5461 return false;
5464 // InsertedTruncs - Only insert one trunc in each block once.
5465 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5467 bool MadeChange = false;
5468 for (Use &U : Src->uses()) {
5469 Instruction *User = cast<Instruction>(U.getUser());
5471 // Figure out which BB this ext is used in.
5472 BasicBlock *UserBB = User->getParent();
5473 if (UserBB == DefBB) continue;
5475 // Both src and def are live in this block. Rewrite the use.
5476 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5478 if (!InsertedTrunc) {
5479 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5480 assert(InsertPt != UserBB->end());
5481 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
5482 InsertedInsts.insert(InsertedTrunc);
5485 // Replace a use of the {s|z}ext source with a use of the result.
5486 U = InsertedTrunc;
5487 ++NumExtUses;
5488 MadeChange = true;
5491 return MadeChange;
5494 // Find loads whose uses only use some of the loaded value's bits. Add an "and"
5495 // just after the load if the target can fold this into one extload instruction,
5496 // with the hope of eliminating some of the other later "and" instructions using
5497 // the loaded value. "and"s that are made trivially redundant by the insertion
5498 // of the new "and" are removed by this function, while others (e.g. those whose
5499 // path from the load goes through a phi) are left for isel to potentially
5500 // remove.
5502 // For example:
5504 // b0:
5505 // x = load i32
5506 // ...
5507 // b1:
5508 // y = and x, 0xff
5509 // z = use y
5511 // becomes:
5513 // b0:
5514 // x = load i32
5515 // x' = and x, 0xff
5516 // ...
5517 // b1:
5518 // z = use x'
5520 // whereas:
5522 // b0:
5523 // x1 = load i32
5524 // ...
5525 // b1:
5526 // x2 = load i32
5527 // ...
5528 // b2:
5529 // x = phi x1, x2
5530 // y = and x, 0xff
5532 // becomes (after a call to optimizeLoadExt for each load):
5534 // b0:
5535 // x1 = load i32
5536 // x1' = and x1, 0xff
5537 // ...
5538 // b1:
5539 // x2 = load i32
5540 // x2' = and x2, 0xff
5541 // ...
5542 // b2:
5543 // x = phi x1', x2'
5544 // y = and x, 0xff
5545 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5546 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
5547 return false;
5549 // Skip loads we've already transformed.
5550 if (Load->hasOneUse() &&
5551 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5552 return false;
5554 // Look at all uses of Load, looking through phis, to determine how many bits
5555 // of the loaded value are needed.
5556 SmallVector<Instruction *, 8> WorkList;
5557 SmallPtrSet<Instruction *, 16> Visited;
5558 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5559 for (auto *U : Load->users())
5560 WorkList.push_back(cast<Instruction>(U));
5562 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5563 unsigned BitWidth = LoadResultVT.getSizeInBits();
5564 APInt DemandBits(BitWidth, 0);
5565 APInt WidestAndBits(BitWidth, 0);
5567 while (!WorkList.empty()) {
5568 Instruction *I = WorkList.back();
5569 WorkList.pop_back();
5571 // Break use-def graph loops.
5572 if (!Visited.insert(I).second)
5573 continue;
5575 // For a PHI node, push all of its users.
5576 if (auto *Phi = dyn_cast<PHINode>(I)) {
5577 for (auto *U : Phi->users())
5578 WorkList.push_back(cast<Instruction>(U));
5579 continue;
5582 switch (I->getOpcode()) {
5583 case Instruction::And: {
5584 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5585 if (!AndC)
5586 return false;
5587 APInt AndBits = AndC->getValue();
5588 DemandBits |= AndBits;
5589 // Keep track of the widest and mask we see.
5590 if (AndBits.ugt(WidestAndBits))
5591 WidestAndBits = AndBits;
5592 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5593 AndsToMaybeRemove.push_back(I);
5594 break;
5597 case Instruction::Shl: {
5598 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5599 if (!ShlC)
5600 return false;
5601 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5602 DemandBits.setLowBits(BitWidth - ShiftAmt);
5603 break;
5606 case Instruction::Trunc: {
5607 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5608 unsigned TruncBitWidth = TruncVT.getSizeInBits();
5609 DemandBits.setLowBits(TruncBitWidth);
5610 break;
5613 default:
5614 return false;
5618 uint32_t ActiveBits = DemandBits.getActiveBits();
5619 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5620 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5621 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5622 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5623 // followed by an AND.
5624 // TODO: Look into removing this restriction by fixing backends to either
5625 // return false for isLoadExtLegal for i1 or have them select this pattern to
5626 // a single instruction.
5628 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5629 // mask, since these are the only ands that will be removed by isel.
5630 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
5631 WidestAndBits != DemandBits)
5632 return false;
5634 LLVMContext &Ctx = Load->getType()->getContext();
5635 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5636 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5638 // Reject cases that won't be matched as extloads.
5639 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5640 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5641 return false;
5643 IRBuilder<> Builder(Load->getNextNode());
5644 auto *NewAnd = dyn_cast<Instruction>(
5645 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5646 // Mark this instruction as "inserted by CGP", so that other
5647 // optimizations don't touch it.
5648 InsertedInsts.insert(NewAnd);
5650 // Replace all uses of load with new and (except for the use of load in the
5651 // new and itself).
5652 Load->replaceAllUsesWith(NewAnd);
5653 NewAnd->setOperand(0, Load);
5655 // Remove any and instructions that are now redundant.
5656 for (auto *And : AndsToMaybeRemove)
5657 // Check that the and mask is the same as the one we decided to put on the
5658 // new and.
5659 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5660 And->replaceAllUsesWith(NewAnd);
5661 if (&*CurInstIterator == And)
5662 CurInstIterator = std::next(And->getIterator());
5663 And->eraseFromParent();
5664 ++NumAndUses;
5667 ++NumAndsAdded;
5668 return true;
5671 /// Check if V (an operand of a select instruction) is an expensive instruction
5672 /// that is only used once.
5673 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5674 auto *I = dyn_cast<Instruction>(V);
5675 // If it's safe to speculatively execute, then it should not have side
5676 // effects; therefore, it's safe to sink and possibly *not* execute.
5677 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5678 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5681 /// Returns true if a SelectInst should be turned into an explicit branch.
5682 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
5683 const TargetLowering *TLI,
5684 SelectInst *SI) {
5685 // If even a predictable select is cheap, then a branch can't be cheaper.
5686 if (!TLI->isPredictableSelectExpensive())
5687 return false;
5689 // FIXME: This should use the same heuristics as IfConversion to determine
5690 // whether a select is better represented as a branch.
5692 // If metadata tells us that the select condition is obviously predictable,
5693 // then we want to replace the select with a branch.
5694 uint64_t TrueWeight, FalseWeight;
5695 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5696 uint64_t Max = std::max(TrueWeight, FalseWeight);
5697 uint64_t Sum = TrueWeight + FalseWeight;
5698 if (Sum != 0) {
5699 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5700 if (Probability > TLI->getPredictableBranchThreshold())
5701 return true;
5705 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5707 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5708 // comparison condition. If the compare has more than one use, there's
5709 // probably another cmov or setcc around, so it's not worth emitting a branch.
5710 if (!Cmp || !Cmp->hasOneUse())
5711 return false;
5713 // If either operand of the select is expensive and only needed on one side
5714 // of the select, we should form a branch.
5715 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5716 sinkSelectOperand(TTI, SI->getFalseValue()))
5717 return true;
5719 return false;
5722 /// If \p isTrue is true, return the true value of \p SI, otherwise return
5723 /// false value of \p SI. If the true/false value of \p SI is defined by any
5724 /// select instructions in \p Selects, look through the defining select
5725 /// instruction until the true/false value is not defined in \p Selects.
5726 static Value *getTrueOrFalseValue(
5727 SelectInst *SI, bool isTrue,
5728 const SmallPtrSet<const Instruction *, 2> &Selects) {
5729 Value *V;
5731 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5732 DefSI = dyn_cast<SelectInst>(V)) {
5733 assert(DefSI->getCondition() == SI->getCondition() &&
5734 "The condition of DefSI does not match with SI");
5735 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5737 return V;
5740 /// If we have a SelectInst that will likely profit from branch prediction,
5741 /// turn it into a branch.
5742 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5743 // If branch conversion isn't desirable, exit early.
5744 if (DisableSelectToBranch || OptSize || !TLI)
5745 return false;
5747 // Find all consecutive select instructions that share the same condition.
5748 SmallVector<SelectInst *, 2> ASI;
5749 ASI.push_back(SI);
5750 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5751 It != SI->getParent()->end(); ++It) {
5752 SelectInst *I = dyn_cast<SelectInst>(&*It);
5753 if (I && SI->getCondition() == I->getCondition()) {
5754 ASI.push_back(I);
5755 } else {
5756 break;
5760 SelectInst *LastSI = ASI.back();
5761 // Increment the current iterator to skip all the rest of select instructions
5762 // because they will be either "not lowered" or "all lowered" to branch.
5763 CurInstIterator = std::next(LastSI->getIterator());
5765 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5767 // Can we convert the 'select' to CF ?
5768 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
5769 return false;
5771 TargetLowering::SelectSupportKind SelectKind;
5772 if (VectorCond)
5773 SelectKind = TargetLowering::VectorMaskSelect;
5774 else if (SI->getType()->isVectorTy())
5775 SelectKind = TargetLowering::ScalarCondVectorVal;
5776 else
5777 SelectKind = TargetLowering::ScalarValSelect;
5779 if (TLI->isSelectSupported(SelectKind) &&
5780 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5781 return false;
5783 ModifiedDT = true;
5785 // Transform a sequence like this:
5786 // start:
5787 // %cmp = cmp uge i32 %a, %b
5788 // %sel = select i1 %cmp, i32 %c, i32 %d
5790 // Into:
5791 // start:
5792 // %cmp = cmp uge i32 %a, %b
5793 // br i1 %cmp, label %select.true, label %select.false
5794 // select.true:
5795 // br label %select.end
5796 // select.false:
5797 // br label %select.end
5798 // select.end:
5799 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5801 // In addition, we may sink instructions that produce %c or %d from
5802 // the entry block into the destination(s) of the new branch.
5803 // If the true or false blocks do not contain a sunken instruction, that
5804 // block and its branch may be optimized away. In that case, one side of the
5805 // first branch will point directly to select.end, and the corresponding PHI
5806 // predecessor block will be the start block.
5808 // First, we split the block containing the select into 2 blocks.
5809 BasicBlock *StartBlock = SI->getParent();
5810 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
5811 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
5813 // Delete the unconditional branch that was just created by the split.
5814 StartBlock->getTerminator()->eraseFromParent();
5816 // These are the new basic blocks for the conditional branch.
5817 // At least one will become an actual new basic block.
5818 BasicBlock *TrueBlock = nullptr;
5819 BasicBlock *FalseBlock = nullptr;
5820 BranchInst *TrueBranch = nullptr;
5821 BranchInst *FalseBranch = nullptr;
5823 // Sink expensive instructions into the conditional blocks to avoid executing
5824 // them speculatively.
5825 for (SelectInst *SI : ASI) {
5826 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5827 if (TrueBlock == nullptr) {
5828 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5829 EndBlock->getParent(), EndBlock);
5830 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5831 TrueBranch->setDebugLoc(SI->getDebugLoc());
5833 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5834 TrueInst->moveBefore(TrueBranch);
5836 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5837 if (FalseBlock == nullptr) {
5838 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5839 EndBlock->getParent(), EndBlock);
5840 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5841 FalseBranch->setDebugLoc(SI->getDebugLoc());
5843 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5844 FalseInst->moveBefore(FalseBranch);
5848 // If there was nothing to sink, then arbitrarily choose the 'false' side
5849 // for a new input value to the PHI.
5850 if (TrueBlock == FalseBlock) {
5851 assert(TrueBlock == nullptr &&
5852 "Unexpected basic block transform while optimizing select");
5854 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5855 EndBlock->getParent(), EndBlock);
5856 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5857 FalseBranch->setDebugLoc(SI->getDebugLoc());
5860 // Insert the real conditional branch based on the original condition.
5861 // If we did not create a new block for one of the 'true' or 'false' paths
5862 // of the condition, it means that side of the branch goes to the end block
5863 // directly and the path originates from the start block from the point of
5864 // view of the new PHI.
5865 BasicBlock *TT, *FT;
5866 if (TrueBlock == nullptr) {
5867 TT = EndBlock;
5868 FT = FalseBlock;
5869 TrueBlock = StartBlock;
5870 } else if (FalseBlock == nullptr) {
5871 TT = TrueBlock;
5872 FT = EndBlock;
5873 FalseBlock = StartBlock;
5874 } else {
5875 TT = TrueBlock;
5876 FT = FalseBlock;
5878 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
5880 SmallPtrSet<const Instruction *, 2> INS;
5881 INS.insert(ASI.begin(), ASI.end());
5882 // Use reverse iterator because later select may use the value of the
5883 // earlier select, and we need to propagate value through earlier select
5884 // to get the PHI operand.
5885 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5886 SelectInst *SI = *It;
5887 // The select itself is replaced with a PHI Node.
5888 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5889 PN->takeName(SI);
5890 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5891 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
5892 PN->setDebugLoc(SI->getDebugLoc());
5894 SI->replaceAllUsesWith(PN);
5895 SI->eraseFromParent();
5896 INS.erase(SI);
5897 ++NumSelectsExpanded;
5900 // Instruct OptimizeBlock to skip to the next block.
5901 CurInstIterator = StartBlock->end();
5902 return true;
5905 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
5906 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5907 int SplatElem = -1;
5908 for (unsigned i = 0; i < Mask.size(); ++i) {
5909 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5910 return false;
5911 SplatElem = Mask[i];
5914 return true;
5917 /// Some targets have expensive vector shifts if the lanes aren't all the same
5918 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5919 /// it's often worth sinking a shufflevector splat down to its use so that
5920 /// codegen can spot all lanes are identical.
5921 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
5922 BasicBlock *DefBB = SVI->getParent();
5924 // Only do this xform if variable vector shifts are particularly expensive.
5925 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5926 return false;
5928 // We only expect better codegen by sinking a shuffle if we can recognise a
5929 // constant splat.
5930 if (!isBroadcastShuffle(SVI))
5931 return false;
5933 // InsertedShuffles - Only insert a shuffle in each block once.
5934 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5936 bool MadeChange = false;
5937 for (User *U : SVI->users()) {
5938 Instruction *UI = cast<Instruction>(U);
5940 // Figure out which BB this ext is used in.
5941 BasicBlock *UserBB = UI->getParent();
5942 if (UserBB == DefBB) continue;
5944 // For now only apply this when the splat is used by a shift instruction.
5945 if (!UI->isShift()) continue;
5947 // Everything checks out, sink the shuffle if the user's block doesn't
5948 // already have a copy.
5949 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5951 if (!InsertedShuffle) {
5952 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5953 assert(InsertPt != UserBB->end());
5954 InsertedShuffle =
5955 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5956 SVI->getOperand(2), "", &*InsertPt);
5959 UI->replaceUsesOfWith(SVI, InsertedShuffle);
5960 MadeChange = true;
5963 // If we removed all uses, nuke the shuffle.
5964 if (SVI->use_empty()) {
5965 SVI->eraseFromParent();
5966 MadeChange = true;
5969 return MadeChange;
5972 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5973 if (!TLI || !DL)
5974 return false;
5976 Value *Cond = SI->getCondition();
5977 Type *OldType = Cond->getType();
5978 LLVMContext &Context = Cond->getContext();
5979 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5980 unsigned RegWidth = RegType.getSizeInBits();
5982 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5983 return false;
5985 // If the register width is greater than the type width, expand the condition
5986 // of the switch instruction and each case constant to the width of the
5987 // register. By widening the type of the switch condition, subsequent
5988 // comparisons (for case comparisons) will not need to be extended to the
5989 // preferred register width, so we will potentially eliminate N-1 extends,
5990 // where N is the number of cases in the switch.
5991 auto *NewType = Type::getIntNTy(Context, RegWidth);
5993 // Zero-extend the switch condition and case constants unless the switch
5994 // condition is a function argument that is already being sign-extended.
5995 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5996 // everything instead.
5997 Instruction::CastOps ExtType = Instruction::ZExt;
5998 if (auto *Arg = dyn_cast<Argument>(Cond))
5999 if (Arg->hasSExtAttr())
6000 ExtType = Instruction::SExt;
6002 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
6003 ExtInst->insertBefore(SI);
6004 ExtInst->setDebugLoc(SI->getDebugLoc());
6005 SI->setCondition(ExtInst);
6006 for (auto Case : SI->cases()) {
6007 APInt NarrowConst = Case.getCaseValue()->getValue();
6008 APInt WideConst = (ExtType == Instruction::ZExt) ?
6009 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
6010 Case.setValue(ConstantInt::get(Context, WideConst));
6013 return true;
6017 namespace {
6019 /// Helper class to promote a scalar operation to a vector one.
6020 /// This class is used to move downward extractelement transition.
6021 /// E.g.,
6022 /// a = vector_op <2 x i32>
6023 /// b = extractelement <2 x i32> a, i32 0
6024 /// c = scalar_op b
6025 /// store c
6027 /// =>
6028 /// a = vector_op <2 x i32>
6029 /// c = vector_op a (equivalent to scalar_op on the related lane)
6030 /// * d = extractelement <2 x i32> c, i32 0
6031 /// * store d
6032 /// Assuming both extractelement and store can be combine, we get rid of the
6033 /// transition.
6034 class VectorPromoteHelper {
6035 /// DataLayout associated with the current module.
6036 const DataLayout &DL;
6038 /// Used to perform some checks on the legality of vector operations.
6039 const TargetLowering &TLI;
6041 /// Used to estimated the cost of the promoted chain.
6042 const TargetTransformInfo &TTI;
6044 /// The transition being moved downwards.
6045 Instruction *Transition;
6047 /// The sequence of instructions to be promoted.
6048 SmallVector<Instruction *, 4> InstsToBePromoted;
6050 /// Cost of combining a store and an extract.
6051 unsigned StoreExtractCombineCost;
6053 /// Instruction that will be combined with the transition.
6054 Instruction *CombineInst = nullptr;
6056 /// The instruction that represents the current end of the transition.
6057 /// Since we are faking the promotion until we reach the end of the chain
6058 /// of computation, we need a way to get the current end of the transition.
6059 Instruction *getEndOfTransition() const {
6060 if (InstsToBePromoted.empty())
6061 return Transition;
6062 return InstsToBePromoted.back();
6065 /// Return the index of the original value in the transition.
6066 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
6067 /// c, is at index 0.
6068 unsigned getTransitionOriginalValueIdx() const {
6069 assert(isa<ExtractElementInst>(Transition) &&
6070 "Other kind of transitions are not supported yet");
6071 return 0;
6074 /// Return the index of the index in the transition.
6075 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
6076 /// is at index 1.
6077 unsigned getTransitionIdx() const {
6078 assert(isa<ExtractElementInst>(Transition) &&
6079 "Other kind of transitions are not supported yet");
6080 return 1;
6083 /// Get the type of the transition.
6084 /// This is the type of the original value.
6085 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
6086 /// transition is <2 x i32>.
6087 Type *getTransitionType() const {
6088 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
6091 /// Promote \p ToBePromoted by moving \p Def downward through.
6092 /// I.e., we have the following sequence:
6093 /// Def = Transition <ty1> a to <ty2>
6094 /// b = ToBePromoted <ty2> Def, ...
6095 /// =>
6096 /// b = ToBePromoted <ty1> a, ...
6097 /// Def = Transition <ty1> ToBePromoted to <ty2>
6098 void promoteImpl(Instruction *ToBePromoted);
6100 /// Check whether or not it is profitable to promote all the
6101 /// instructions enqueued to be promoted.
6102 bool isProfitableToPromote() {
6103 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
6104 unsigned Index = isa<ConstantInt>(ValIdx)
6105 ? cast<ConstantInt>(ValIdx)->getZExtValue()
6106 : -1;
6107 Type *PromotedType = getTransitionType();
6109 StoreInst *ST = cast<StoreInst>(CombineInst);
6110 unsigned AS = ST->getPointerAddressSpace();
6111 unsigned Align = ST->getAlignment();
6112 // Check if this store is supported.
6113 if (!TLI.allowsMisalignedMemoryAccesses(
6114 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
6115 Align)) {
6116 // If this is not supported, there is no way we can combine
6117 // the extract with the store.
6118 return false;
6121 // The scalar chain of computation has to pay for the transition
6122 // scalar to vector.
6123 // The vector chain has to account for the combining cost.
6124 uint64_t ScalarCost =
6125 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
6126 uint64_t VectorCost = StoreExtractCombineCost;
6127 for (const auto &Inst : InstsToBePromoted) {
6128 // Compute the cost.
6129 // By construction, all instructions being promoted are arithmetic ones.
6130 // Moreover, one argument is a constant that can be viewed as a splat
6131 // constant.
6132 Value *Arg0 = Inst->getOperand(0);
6133 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
6134 isa<ConstantFP>(Arg0);
6135 TargetTransformInfo::OperandValueKind Arg0OVK =
6136 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6137 : TargetTransformInfo::OK_AnyValue;
6138 TargetTransformInfo::OperandValueKind Arg1OVK =
6139 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6140 : TargetTransformInfo::OK_AnyValue;
6141 ScalarCost += TTI.getArithmeticInstrCost(
6142 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
6143 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
6144 Arg0OVK, Arg1OVK);
6146 LLVM_DEBUG(
6147 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
6148 << ScalarCost << "\nVector: " << VectorCost << '\n');
6149 return ScalarCost > VectorCost;
6152 /// Generate a constant vector with \p Val with the same
6153 /// number of elements as the transition.
6154 /// \p UseSplat defines whether or not \p Val should be replicated
6155 /// across the whole vector.
6156 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
6157 /// otherwise we generate a vector with as many undef as possible:
6158 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
6159 /// used at the index of the extract.
6160 Value *getConstantVector(Constant *Val, bool UseSplat) const {
6161 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
6162 if (!UseSplat) {
6163 // If we cannot determine where the constant must be, we have to
6164 // use a splat constant.
6165 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
6166 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6167 ExtractIdx = CstVal->getSExtValue();
6168 else
6169 UseSplat = true;
6172 unsigned End = getTransitionType()->getVectorNumElements();
6173 if (UseSplat)
6174 return ConstantVector::getSplat(End, Val);
6176 SmallVector<Constant *, 4> ConstVec;
6177 UndefValue *UndefVal = UndefValue::get(Val->getType());
6178 for (unsigned Idx = 0; Idx != End; ++Idx) {
6179 if (Idx == ExtractIdx)
6180 ConstVec.push_back(Val);
6181 else
6182 ConstVec.push_back(UndefVal);
6184 return ConstantVector::get(ConstVec);
6187 /// Check if promoting to a vector type an operand at \p OperandIdx
6188 /// in \p Use can trigger undefined behavior.
6189 static bool canCauseUndefinedBehavior(const Instruction *Use,
6190 unsigned OperandIdx) {
6191 // This is not safe to introduce undef when the operand is on
6192 // the right hand side of a division-like instruction.
6193 if (OperandIdx != 1)
6194 return false;
6195 switch (Use->getOpcode()) {
6196 default:
6197 return false;
6198 case Instruction::SDiv:
6199 case Instruction::UDiv:
6200 case Instruction::SRem:
6201 case Instruction::URem:
6202 return true;
6203 case Instruction::FDiv:
6204 case Instruction::FRem:
6205 return !Use->hasNoNaNs();
6207 llvm_unreachable(nullptr);
6210 public:
6211 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6212 const TargetTransformInfo &TTI, Instruction *Transition,
6213 unsigned CombineCost)
6214 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
6215 StoreExtractCombineCost(CombineCost) {
6216 assert(Transition && "Do not know how to promote null");
6219 /// Check if we can promote \p ToBePromoted to \p Type.
6220 bool canPromote(const Instruction *ToBePromoted) const {
6221 // We could support CastInst too.
6222 return isa<BinaryOperator>(ToBePromoted);
6225 /// Check if it is profitable to promote \p ToBePromoted
6226 /// by moving downward the transition through.
6227 bool shouldPromote(const Instruction *ToBePromoted) const {
6228 // Promote only if all the operands can be statically expanded.
6229 // Indeed, we do not want to introduce any new kind of transitions.
6230 for (const Use &U : ToBePromoted->operands()) {
6231 const Value *Val = U.get();
6232 if (Val == getEndOfTransition()) {
6233 // If the use is a division and the transition is on the rhs,
6234 // we cannot promote the operation, otherwise we may create a
6235 // division by zero.
6236 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6237 return false;
6238 continue;
6240 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6241 !isa<ConstantFP>(Val))
6242 return false;
6244 // Check that the resulting operation is legal.
6245 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6246 if (!ISDOpcode)
6247 return false;
6248 return StressStoreExtract ||
6249 TLI.isOperationLegalOrCustom(
6250 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
6253 /// Check whether or not \p Use can be combined
6254 /// with the transition.
6255 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6256 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6258 /// Record \p ToBePromoted as part of the chain to be promoted.
6259 void enqueueForPromotion(Instruction *ToBePromoted) {
6260 InstsToBePromoted.push_back(ToBePromoted);
6263 /// Set the instruction that will be combined with the transition.
6264 void recordCombineInstruction(Instruction *ToBeCombined) {
6265 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6266 CombineInst = ToBeCombined;
6269 /// Promote all the instructions enqueued for promotion if it is
6270 /// is profitable.
6271 /// \return True if the promotion happened, false otherwise.
6272 bool promote() {
6273 // Check if there is something to promote.
6274 // Right now, if we do not have anything to combine with,
6275 // we assume the promotion is not profitable.
6276 if (InstsToBePromoted.empty() || !CombineInst)
6277 return false;
6279 // Check cost.
6280 if (!StressStoreExtract && !isProfitableToPromote())
6281 return false;
6283 // Promote.
6284 for (auto &ToBePromoted : InstsToBePromoted)
6285 promoteImpl(ToBePromoted);
6286 InstsToBePromoted.clear();
6287 return true;
6291 } // end anonymous namespace
6293 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6294 // At this point, we know that all the operands of ToBePromoted but Def
6295 // can be statically promoted.
6296 // For Def, we need to use its parameter in ToBePromoted:
6297 // b = ToBePromoted ty1 a
6298 // Def = Transition ty1 b to ty2
6299 // Move the transition down.
6300 // 1. Replace all uses of the promoted operation by the transition.
6301 // = ... b => = ... Def.
6302 assert(ToBePromoted->getType() == Transition->getType() &&
6303 "The type of the result of the transition does not match "
6304 "the final type");
6305 ToBePromoted->replaceAllUsesWith(Transition);
6306 // 2. Update the type of the uses.
6307 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6308 Type *TransitionTy = getTransitionType();
6309 ToBePromoted->mutateType(TransitionTy);
6310 // 3. Update all the operands of the promoted operation with promoted
6311 // operands.
6312 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6313 for (Use &U : ToBePromoted->operands()) {
6314 Value *Val = U.get();
6315 Value *NewVal = nullptr;
6316 if (Val == Transition)
6317 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6318 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6319 isa<ConstantFP>(Val)) {
6320 // Use a splat constant if it is not safe to use undef.
6321 NewVal = getConstantVector(
6322 cast<Constant>(Val),
6323 isa<UndefValue>(Val) ||
6324 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6325 } else
6326 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6327 "this?");
6328 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6330 Transition->moveAfter(ToBePromoted);
6331 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6334 /// Some targets can do store(extractelement) with one instruction.
6335 /// Try to push the extractelement towards the stores when the target
6336 /// has this feature and this is profitable.
6337 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
6338 unsigned CombineCost = std::numeric_limits<unsigned>::max();
6339 if (DisableStoreExtract || !TLI ||
6340 (!StressStoreExtract &&
6341 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6342 Inst->getOperand(1), CombineCost)))
6343 return false;
6345 // At this point we know that Inst is a vector to scalar transition.
6346 // Try to move it down the def-use chain, until:
6347 // - We can combine the transition with its single use
6348 // => we got rid of the transition.
6349 // - We escape the current basic block
6350 // => we would need to check that we are moving it at a cheaper place and
6351 // we do not do that for now.
6352 BasicBlock *Parent = Inst->getParent();
6353 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
6354 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
6355 // If the transition has more than one use, assume this is not going to be
6356 // beneficial.
6357 while (Inst->hasOneUse()) {
6358 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
6359 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
6361 if (ToBePromoted->getParent() != Parent) {
6362 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6363 << ToBePromoted->getParent()->getName()
6364 << ") than the transition (" << Parent->getName()
6365 << ").\n");
6366 return false;
6369 if (VPH.canCombine(ToBePromoted)) {
6370 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6371 << "will be combined with: " << *ToBePromoted << '\n');
6372 VPH.recordCombineInstruction(ToBePromoted);
6373 bool Changed = VPH.promote();
6374 NumStoreExtractExposed += Changed;
6375 return Changed;
6378 LLVM_DEBUG(dbgs() << "Try promoting.\n");
6379 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6380 return false;
6382 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
6384 VPH.enqueueForPromotion(ToBePromoted);
6385 Inst = ToBePromoted;
6387 return false;
6390 /// For the instruction sequence of store below, F and I values
6391 /// are bundled together as an i64 value before being stored into memory.
6392 /// Sometimes it is more efficient to generate separate stores for F and I,
6393 /// which can remove the bitwise instructions or sink them to colder places.
6395 /// (store (or (zext (bitcast F to i32) to i64),
6396 /// (shl (zext I to i64), 32)), addr) -->
6397 /// (store F, addr) and (store I, addr+4)
6399 /// Similarly, splitting for other merged store can also be beneficial, like:
6400 /// For pair of {i32, i32}, i64 store --> two i32 stores.
6401 /// For pair of {i32, i16}, i64 store --> two i32 stores.
6402 /// For pair of {i16, i16}, i32 store --> two i16 stores.
6403 /// For pair of {i16, i8}, i32 store --> two i16 stores.
6404 /// For pair of {i8, i8}, i16 store --> two i8 stores.
6406 /// We allow each target to determine specifically which kind of splitting is
6407 /// supported.
6409 /// The store patterns are commonly seen from the simple code snippet below
6410 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6411 /// void goo(const std::pair<int, float> &);
6412 /// hoo() {
6413 /// ...
6414 /// goo(std::make_pair(tmp, ftmp));
6415 /// ...
6416 /// }
6418 /// Although we already have similar splitting in DAG Combine, we duplicate
6419 /// it in CodeGenPrepare to catch the case in which pattern is across
6420 /// multiple BBs. The logic in DAG Combine is kept to catch case generated
6421 /// during code expansion.
6422 static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6423 const TargetLowering &TLI) {
6424 // Handle simple but common cases only.
6425 Type *StoreType = SI.getValueOperand()->getType();
6426 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6427 DL.getTypeSizeInBits(StoreType) == 0)
6428 return false;
6430 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6431 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6432 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6433 DL.getTypeSizeInBits(SplitStoreType))
6434 return false;
6436 // Match the following patterns:
6437 // (store (or (zext LValue to i64),
6438 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6439 // or
6440 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6441 // (zext LValue to i64),
6442 // Expect both operands of OR and the first operand of SHL have only
6443 // one use.
6444 Value *LValue, *HValue;
6445 if (!match(SI.getValueOperand(),
6446 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6447 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6448 m_SpecificInt(HalfValBitSize))))))
6449 return false;
6451 // Check LValue and HValue are int with size less or equal than 32.
6452 if (!LValue->getType()->isIntegerTy() ||
6453 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6454 !HValue->getType()->isIntegerTy() ||
6455 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6456 return false;
6458 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6459 // as the input of target query.
6460 auto *LBC = dyn_cast<BitCastInst>(LValue);
6461 auto *HBC = dyn_cast<BitCastInst>(HValue);
6462 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6463 : EVT::getEVT(LValue->getType());
6464 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6465 : EVT::getEVT(HValue->getType());
6466 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6467 return false;
6469 // Start to split store.
6470 IRBuilder<> Builder(SI.getContext());
6471 Builder.SetInsertPoint(&SI);
6473 // If LValue/HValue is a bitcast in another BB, create a new one in current
6474 // BB so it may be merged with the splitted stores by dag combiner.
6475 if (LBC && LBC->getParent() != SI.getParent())
6476 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6477 if (HBC && HBC->getParent() != SI.getParent())
6478 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6480 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
6481 auto CreateSplitStore = [&](Value *V, bool Upper) {
6482 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6483 Value *Addr = Builder.CreateBitCast(
6484 SI.getOperand(1),
6485 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6486 if ((IsLE && Upper) || (!IsLE && !Upper))
6487 Addr = Builder.CreateGEP(
6488 SplitStoreType, Addr,
6489 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6490 Builder.CreateAlignedStore(
6491 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6494 CreateSplitStore(LValue, false);
6495 CreateSplitStore(HValue, true);
6497 // Delete the old store.
6498 SI.eraseFromParent();
6499 return true;
6502 // Return true if the GEP has two operands, the first operand is of a sequential
6503 // type, and the second operand is a constant.
6504 static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6505 gep_type_iterator I = gep_type_begin(*GEP);
6506 return GEP->getNumOperands() == 2 &&
6507 I.isSequential() &&
6508 isa<ConstantInt>(GEP->getOperand(1));
6511 // Try unmerging GEPs to reduce liveness interference (register pressure) across
6512 // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6513 // reducing liveness interference across those edges benefits global register
6514 // allocation. Currently handles only certain cases.
6516 // For example, unmerge %GEPI and %UGEPI as below.
6518 // ---------- BEFORE ----------
6519 // SrcBlock:
6520 // ...
6521 // %GEPIOp = ...
6522 // ...
6523 // %GEPI = gep %GEPIOp, Idx
6524 // ...
6525 // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6526 // (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6527 // (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6528 // %UGEPI)
6530 // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6531 // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6532 // ...
6534 // DstBi:
6535 // ...
6536 // %UGEPI = gep %GEPIOp, UIdx
6537 // ...
6538 // ---------------------------
6540 // ---------- AFTER ----------
6541 // SrcBlock:
6542 // ... (same as above)
6543 // (* %GEPI is still alive on the indirectbr edges)
6544 // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6545 // unmerging)
6546 // ...
6548 // DstBi:
6549 // ...
6550 // %UGEPI = gep %GEPI, (UIdx-Idx)
6551 // ...
6552 // ---------------------------
6554 // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6555 // no longer alive on them.
6557 // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6558 // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6559 // not to disable further simplications and optimizations as a result of GEP
6560 // merging.
6562 // Note this unmerging may increase the length of the data flow critical path
6563 // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6564 // between the register pressure and the length of data-flow critical
6565 // path. Restricting this to the uncommon IndirectBr case would minimize the
6566 // impact of potentially longer critical path, if any, and the impact on compile
6567 // time.
6568 static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6569 const TargetTransformInfo *TTI) {
6570 BasicBlock *SrcBlock = GEPI->getParent();
6571 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6572 // (non-IndirectBr) cases exit early here.
6573 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6574 return false;
6575 // Check that GEPI is a simple gep with a single constant index.
6576 if (!GEPSequentialConstIndexed(GEPI))
6577 return false;
6578 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6579 // Check that GEPI is a cheap one.
6580 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6581 > TargetTransformInfo::TCC_Basic)
6582 return false;
6583 Value *GEPIOp = GEPI->getOperand(0);
6584 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6585 if (!isa<Instruction>(GEPIOp))
6586 return false;
6587 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6588 if (GEPIOpI->getParent() != SrcBlock)
6589 return false;
6590 // Check that GEP is used outside the block, meaning it's alive on the
6591 // IndirectBr edge(s).
6592 if (find_if(GEPI->users(), [&](User *Usr) {
6593 if (auto *I = dyn_cast<Instruction>(Usr)) {
6594 if (I->getParent() != SrcBlock) {
6595 return true;
6598 return false;
6599 }) == GEPI->users().end())
6600 return false;
6601 // The second elements of the GEP chains to be unmerged.
6602 std::vector<GetElementPtrInst *> UGEPIs;
6603 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6604 // on IndirectBr edges.
6605 for (User *Usr : GEPIOp->users()) {
6606 if (Usr == GEPI) continue;
6607 // Check if Usr is an Instruction. If not, give up.
6608 if (!isa<Instruction>(Usr))
6609 return false;
6610 auto *UI = cast<Instruction>(Usr);
6611 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6612 if (UI->getParent() == SrcBlock)
6613 continue;
6614 // Check if Usr is a GEP. If not, give up.
6615 if (!isa<GetElementPtrInst>(Usr))
6616 return false;
6617 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6618 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6619 // the pointer operand to it. If so, record it in the vector. If not, give
6620 // up.
6621 if (!GEPSequentialConstIndexed(UGEPI))
6622 return false;
6623 if (UGEPI->getOperand(0) != GEPIOp)
6624 return false;
6625 if (GEPIIdx->getType() !=
6626 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6627 return false;
6628 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6629 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6630 > TargetTransformInfo::TCC_Basic)
6631 return false;
6632 UGEPIs.push_back(UGEPI);
6634 if (UGEPIs.size() == 0)
6635 return false;
6636 // Check the materializing cost of (Uidx-Idx).
6637 for (GetElementPtrInst *UGEPI : UGEPIs) {
6638 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6639 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6640 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6641 if (ImmCost > TargetTransformInfo::TCC_Basic)
6642 return false;
6644 // Now unmerge between GEPI and UGEPIs.
6645 for (GetElementPtrInst *UGEPI : UGEPIs) {
6646 UGEPI->setOperand(0, GEPI);
6647 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6648 Constant *NewUGEPIIdx =
6649 ConstantInt::get(GEPIIdx->getType(),
6650 UGEPIIdx->getValue() - GEPIIdx->getValue());
6651 UGEPI->setOperand(1, NewUGEPIIdx);
6652 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6653 // inbounds to avoid UB.
6654 if (!GEPI->isInBounds()) {
6655 UGEPI->setIsInBounds(false);
6658 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6659 // alive on IndirectBr edges).
6660 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6661 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6662 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6663 return true;
6666 bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
6667 // Bail out if we inserted the instruction to prevent optimizations from
6668 // stepping on each other's toes.
6669 if (InsertedInsts.count(I))
6670 return false;
6672 if (PHINode *P = dyn_cast<PHINode>(I)) {
6673 // It is possible for very late stage optimizations (such as SimplifyCFG)
6674 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6675 // trivial PHI, go ahead and zap it here.
6676 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
6677 P->replaceAllUsesWith(V);
6678 P->eraseFromParent();
6679 ++NumPHIsElim;
6680 return true;
6682 return false;
6685 if (CastInst *CI = dyn_cast<CastInst>(I)) {
6686 // If the source of the cast is a constant, then this should have
6687 // already been constant folded. The only reason NOT to constant fold
6688 // it is if something (e.g. LSR) was careful to place the constant
6689 // evaluation in a block other than then one that uses it (e.g. to hoist
6690 // the address of globals out of a loop). If this is the case, we don't
6691 // want to forward-subst the cast.
6692 if (isa<Constant>(CI->getOperand(0)))
6693 return false;
6695 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
6696 return true;
6698 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6699 /// Sink a zext or sext into its user blocks if the target type doesn't
6700 /// fit in one register
6701 if (TLI &&
6702 TLI->getTypeAction(CI->getContext(),
6703 TLI->getValueType(*DL, CI->getType())) ==
6704 TargetLowering::TypeExpandInteger) {
6705 return SinkCast(CI);
6706 } else {
6707 bool MadeChange = optimizeExt(I);
6708 return MadeChange | optimizeExtUses(I);
6711 return false;
6714 if (CmpInst *CI = dyn_cast<CmpInst>(I))
6715 if (!TLI || !TLI->hasMultipleConditionRegisters())
6716 return OptimizeCmpExpression(CI, TLI);
6718 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6719 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
6720 if (TLI) {
6721 bool Modified = optimizeLoadExt(LI);
6722 unsigned AS = LI->getPointerAddressSpace();
6723 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6724 return Modified;
6726 return false;
6729 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6730 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6731 return true;
6732 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
6733 if (TLI) {
6734 unsigned AS = SI->getPointerAddressSpace();
6735 return optimizeMemoryInst(I, SI->getOperand(1),
6736 SI->getOperand(0)->getType(), AS);
6738 return false;
6741 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6742 unsigned AS = RMW->getPointerAddressSpace();
6743 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6744 RMW->getType(), AS);
6747 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6748 unsigned AS = CmpX->getPointerAddressSpace();
6749 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6750 CmpX->getCompareOperand()->getType(), AS);
6753 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6755 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6756 EnableAndCmpSinking && TLI)
6757 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6759 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6760 BinOp->getOpcode() == Instruction::LShr)) {
6761 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6762 if (TLI && CI && TLI->hasExtractBitsInsn())
6763 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
6765 return false;
6768 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
6769 if (GEPI->hasAllZeroIndices()) {
6770 /// The GEP operand must be a pointer, so must its result -> BitCast
6771 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6772 GEPI->getName(), GEPI);
6773 NC->setDebugLoc(GEPI->getDebugLoc());
6774 GEPI->replaceAllUsesWith(NC);
6775 GEPI->eraseFromParent();
6776 ++NumGEPsElim;
6777 optimizeInst(NC, ModifiedDT);
6778 return true;
6780 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6781 return true;
6783 return false;
6786 if (CallInst *CI = dyn_cast<CallInst>(I))
6787 return optimizeCallInst(CI, ModifiedDT);
6789 if (SelectInst *SI = dyn_cast<SelectInst>(I))
6790 return optimizeSelectInst(SI);
6792 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
6793 return optimizeShuffleVectorInst(SVI);
6795 if (auto *Switch = dyn_cast<SwitchInst>(I))
6796 return optimizeSwitchInst(Switch);
6798 if (isa<ExtractElementInst>(I))
6799 return optimizeExtractElementInst(I);
6801 return false;
6804 /// Given an OR instruction, check to see if this is a bitreverse
6805 /// idiom. If so, insert the new intrinsic and return true.
6806 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6807 const TargetLowering &TLI) {
6808 if (!I.getType()->isIntegerTy() ||
6809 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6810 TLI.getValueType(DL, I.getType(), true)))
6811 return false;
6813 SmallVector<Instruction*, 4> Insts;
6814 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
6815 return false;
6816 Instruction *LastInst = Insts.back();
6817 I.replaceAllUsesWith(LastInst);
6818 RecursivelyDeleteTriviallyDeadInstructions(&I);
6819 return true;
6822 // In this pass we look for GEP and cast instructions that are used
6823 // across basic blocks and rewrite them to improve basic-block-at-a-time
6824 // selection.
6825 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
6826 SunkAddrs.clear();
6827 bool MadeChange = false;
6829 CurInstIterator = BB.begin();
6830 while (CurInstIterator != BB.end()) {
6831 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6832 if (ModifiedDT)
6833 return true;
6836 bool MadeBitReverse = true;
6837 while (TLI && MadeBitReverse) {
6838 MadeBitReverse = false;
6839 for (auto &I : reverse(BB)) {
6840 if (makeBitReverse(I, *DL, *TLI)) {
6841 MadeBitReverse = MadeChange = true;
6842 ModifiedDT = true;
6843 break;
6847 MadeChange |= dupRetToEnableTailCallOpts(&BB);
6849 return MadeChange;
6852 // llvm.dbg.value is far away from the value then iSel may not be able
6853 // handle it properly. iSel will drop llvm.dbg.value if it can not
6854 // find a node corresponding to the value.
6855 bool CodeGenPrepare::placeDbgValues(Function &F) {
6856 bool MadeChange = false;
6857 for (BasicBlock &BB : F) {
6858 Instruction *PrevNonDbgInst = nullptr;
6859 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
6860 Instruction *Insn = &*BI++;
6861 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
6862 // Leave dbg.values that refer to an alloca alone. These
6863 // intrinsics describe the address of a variable (= the alloca)
6864 // being taken. They should not be moved next to the alloca
6865 // (and to the beginning of the scope), but rather stay close to
6866 // where said address is used.
6867 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
6868 PrevNonDbgInst = Insn;
6869 continue;
6872 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6873 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
6874 // If VI is a phi in a block with an EHPad terminator, we can't insert
6875 // after it.
6876 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6877 continue;
6878 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
6879 << *DVI << ' ' << *VI);
6880 DVI->removeFromParent();
6881 if (isa<PHINode>(VI))
6882 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6883 else
6884 DVI->insertAfter(VI);
6885 MadeChange = true;
6886 ++NumDbgValueMoved;
6890 return MadeChange;
6893 /// Scale down both weights to fit into uint32_t.
6894 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6895 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6896 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
6897 NewTrue = NewTrue / Scale;
6898 NewFalse = NewFalse / Scale;
6901 /// Some targets prefer to split a conditional branch like:
6902 /// \code
6903 /// %0 = icmp ne i32 %a, 0
6904 /// %1 = icmp ne i32 %b, 0
6905 /// %or.cond = or i1 %0, %1
6906 /// br i1 %or.cond, label %TrueBB, label %FalseBB
6907 /// \endcode
6908 /// into multiple branch instructions like:
6909 /// \code
6910 /// bb1:
6911 /// %0 = icmp ne i32 %a, 0
6912 /// br i1 %0, label %TrueBB, label %bb2
6913 /// bb2:
6914 /// %1 = icmp ne i32 %b, 0
6915 /// br i1 %1, label %TrueBB, label %FalseBB
6916 /// \endcode
6917 /// This usually allows instruction selection to do even further optimizations
6918 /// and combine the compare with the branch instruction. Currently this is
6919 /// applied for targets which have "cheap" jump instructions.
6921 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6923 bool CodeGenPrepare::splitBranchCondition(Function &F) {
6924 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
6925 return false;
6927 bool MadeChange = false;
6928 for (auto &BB : F) {
6929 // Does this BB end with the following?
6930 // %cond1 = icmp|fcmp|binary instruction ...
6931 // %cond2 = icmp|fcmp|binary instruction ...
6932 // %cond.or = or|and i1 %cond1, cond2
6933 // br i1 %cond.or label %dest1, label %dest2"
6934 BinaryOperator *LogicOp;
6935 BasicBlock *TBB, *FBB;
6936 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6937 continue;
6939 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6940 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6941 continue;
6943 unsigned Opc;
6944 Value *Cond1, *Cond2;
6945 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6946 m_OneUse(m_Value(Cond2)))))
6947 Opc = Instruction::And;
6948 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6949 m_OneUse(m_Value(Cond2)))))
6950 Opc = Instruction::Or;
6951 else
6952 continue;
6954 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6955 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6956 continue;
6958 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6960 // Create a new BB.
6961 auto TmpBB =
6962 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6963 BB.getParent(), BB.getNextNode());
6965 // Update original basic block by using the first condition directly by the
6966 // branch instruction and removing the no longer needed and/or instruction.
6967 Br1->setCondition(Cond1);
6968 LogicOp->eraseFromParent();
6970 // Depending on the condition we have to either replace the true or the
6971 // false successor of the original branch instruction.
6972 if (Opc == Instruction::And)
6973 Br1->setSuccessor(0, TmpBB);
6974 else
6975 Br1->setSuccessor(1, TmpBB);
6977 // Fill in the new basic block.
6978 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6979 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6980 I->removeFromParent();
6981 I->insertBefore(Br2);
6984 // Update PHI nodes in both successors. The original BB needs to be
6985 // replaced in one successor's PHI nodes, because the branch comes now from
6986 // the newly generated BB (NewBB). In the other successor we need to add one
6987 // incoming edge to the PHI nodes, because both branch instructions target
6988 // now the same successor. Depending on the original branch condition
6989 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6990 // we perform the correct update for the PHI nodes.
6991 // This doesn't change the successor order of the just created branch
6992 // instruction (or any other instruction).
6993 if (Opc == Instruction::Or)
6994 std::swap(TBB, FBB);
6996 // Replace the old BB with the new BB.
6997 for (PHINode &PN : TBB->phis()) {
6998 int i;
6999 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
7000 PN.setIncomingBlock(i, TmpBB);
7003 // Add another incoming edge form the new BB.
7004 for (PHINode &PN : FBB->phis()) {
7005 auto *Val = PN.getIncomingValueForBlock(&BB);
7006 PN.addIncoming(Val, TmpBB);
7009 // Update the branch weights (from SelectionDAGBuilder::
7010 // FindMergedConditions).
7011 if (Opc == Instruction::Or) {
7012 // Codegen X | Y as:
7013 // BB1:
7014 // jmp_if_X TBB
7015 // jmp TmpBB
7016 // TmpBB:
7017 // jmp_if_Y TBB
7018 // jmp FBB
7021 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
7022 // The requirement is that
7023 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
7024 // = TrueProb for original BB.
7025 // Assuming the original weights are A and B, one choice is to set BB1's
7026 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
7027 // assumes that
7028 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
7029 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
7030 // TmpBB, but the math is more complicated.
7031 uint64_t TrueWeight, FalseWeight;
7032 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
7033 uint64_t NewTrueWeight = TrueWeight;
7034 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
7035 scaleWeights(NewTrueWeight, NewFalseWeight);
7036 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7037 .createBranchWeights(TrueWeight, FalseWeight));
7039 NewTrueWeight = TrueWeight;
7040 NewFalseWeight = 2 * FalseWeight;
7041 scaleWeights(NewTrueWeight, NewFalseWeight);
7042 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7043 .createBranchWeights(TrueWeight, FalseWeight));
7045 } else {
7046 // Codegen X & Y as:
7047 // BB1:
7048 // jmp_if_X TmpBB
7049 // jmp FBB
7050 // TmpBB:
7051 // jmp_if_Y TBB
7052 // jmp FBB
7054 // This requires creation of TmpBB after CurBB.
7056 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
7057 // The requirement is that
7058 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
7059 // = FalseProb for original BB.
7060 // Assuming the original weights are A and B, one choice is to set BB1's
7061 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
7062 // assumes that
7063 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
7064 uint64_t TrueWeight, FalseWeight;
7065 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
7066 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
7067 uint64_t NewFalseWeight = FalseWeight;
7068 scaleWeights(NewTrueWeight, NewFalseWeight);
7069 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7070 .createBranchWeights(TrueWeight, FalseWeight));
7072 NewTrueWeight = 2 * TrueWeight;
7073 NewFalseWeight = FalseWeight;
7074 scaleWeights(NewTrueWeight, NewFalseWeight);
7075 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7076 .createBranchWeights(TrueWeight, FalseWeight));
7080 // Note: No point in getting fancy here, since the DT info is never
7081 // available to CodeGenPrepare.
7082 ModifiedDT = true;
7084 MadeChange = true;
7086 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
7087 TmpBB->dump());
7089 return MadeChange;