1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
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 implements routines for translating functions from LLVM IR into
10 // Machine IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/FunctionLoweringInfo.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
17 #include "llvm/CodeGen/Analysis.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/TargetFrameLowering.h"
23 #include "llvm/CodeGen/TargetInstrInfo.h"
24 #include "llvm/CodeGen/TargetLowering.h"
25 #include "llvm/CodeGen/TargetRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/CodeGen/WasmEHFuncInfo.h"
28 #include "llvm/CodeGen/WinEHFuncInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include <algorithm>
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "function-lowering-info"
45 
46 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
47 /// PHI nodes or outside of the basic block that defines it, or used by a
48 /// switch or atomic instruction, which may expand to multiple basic blocks.
isUsedOutsideOfDefiningBlock(const Instruction * I)49 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
50   if (I->use_empty()) return false;
51   if (isa<PHINode>(I)) return true;
52   const BasicBlock *BB = I->getParent();
53   for (const User *U : I->users())
54     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
55       return true;
56 
57   return false;
58 }
59 
getPreferredExtendForValue(const Value * V)60 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
61   // For the users of the source value being used for compare instruction, if
62   // the number of signed predicate is greater than unsigned predicate, we
63   // prefer to use SIGN_EXTEND.
64   //
65   // With this optimization, we would be able to reduce some redundant sign or
66   // zero extension instruction, and eventually more machine CSE opportunities
67   // can be exposed.
68   ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
69   unsigned NumOfSigned = 0, NumOfUnsigned = 0;
70   for (const User *U : V->users()) {
71     if (const auto *CI = dyn_cast<CmpInst>(U)) {
72       NumOfSigned += CI->isSigned();
73       NumOfUnsigned += CI->isUnsigned();
74     }
75   }
76   if (NumOfSigned > NumOfUnsigned)
77     ExtendKind = ISD::SIGN_EXTEND;
78 
79   return ExtendKind;
80 }
81 
set(const Function & fn,MachineFunction & mf,SelectionDAG * DAG)82 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
83                                SelectionDAG *DAG) {
84   Fn = &fn;
85   MF = &mf;
86   TLI = MF->getSubtarget().getTargetLowering();
87   RegInfo = &MF->getRegInfo();
88   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
89   DA = DAG->getDivergenceAnalysis();
90 
91   // Check whether the function can return without sret-demotion.
92   SmallVector<ISD::OutputArg, 4> Outs;
93   CallingConv::ID CC = Fn->getCallingConv();
94 
95   GetReturnInfo(CC, Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI,
96                 mf.getDataLayout());
97   CanLowerReturn =
98       TLI->CanLowerReturn(CC, *MF, Fn->isVarArg(), Outs, Fn->getContext());
99 
100   // If this personality uses funclets, we need to do a bit more work.
101   DenseMap<const AllocaInst *, TinyPtrVector<int *>> CatchObjects;
102   EHPersonality Personality = classifyEHPersonality(
103       Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr);
104   if (isFuncletEHPersonality(Personality)) {
105     // Calculate state numbers if we haven't already.
106     WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
107     if (Personality == EHPersonality::MSVC_CXX)
108       calculateWinCXXEHStateNumbers(&fn, EHInfo);
109     else if (isAsynchronousEHPersonality(Personality))
110       calculateSEHStateNumbers(&fn, EHInfo);
111     else if (Personality == EHPersonality::CoreCLR)
112       calculateClrEHStateNumbers(&fn, EHInfo);
113 
114     // Map all BB references in the WinEH data to MBBs.
115     for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
116       for (WinEHHandlerType &H : TBME.HandlerArray) {
117         if (const AllocaInst *AI = H.CatchObj.Alloca)
118           CatchObjects.insert({AI, {}}).first->second.push_back(
119               &H.CatchObj.FrameIndex);
120         else
121           H.CatchObj.FrameIndex = INT_MAX;
122       }
123     }
124   }
125   if (Personality == EHPersonality::Wasm_CXX) {
126     WasmEHFuncInfo &EHInfo = *MF->getWasmEHFuncInfo();
127     calculateWasmEHInfo(&fn, EHInfo);
128   }
129 
130   // Initialize the mapping of values to registers.  This is only set up for
131   // instruction values that are used outside of the block that defines
132   // them.
133   const Align StackAlign = TFI->getStackAlign();
134   for (const BasicBlock &BB : *Fn) {
135     for (const Instruction &I : BB) {
136       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
137         Type *Ty = AI->getAllocatedType();
138         Align TyPrefAlign = MF->getDataLayout().getPrefTypeAlign(Ty);
139         // The "specified" alignment is the alignment written on the alloca,
140         // or the preferred alignment of the type if none is specified.
141         //
142         // (Unspecified alignment on allocas will be going away soon.)
143         Align SpecifiedAlign = AI->getAlign();
144 
145         // If the preferred alignment of the type is higher than the specified
146         // alignment of the alloca, promote the alignment, as long as it doesn't
147         // require realigning the stack.
148         //
149         // FIXME: Do we really want to second-guess the IR in isel?
150         Align Alignment =
151             std::max(std::min(TyPrefAlign, StackAlign), SpecifiedAlign);
152 
153         // Static allocas can be folded into the initial stack frame
154         // adjustment. For targets that don't realign the stack, don't
155         // do this if there is an extra alignment requirement.
156         if (AI->isStaticAlloca() &&
157             (TFI->isStackRealignable() || (Alignment <= StackAlign))) {
158           const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
159           uint64_t TySize =
160               MF->getDataLayout().getTypeAllocSize(Ty).getKnownMinSize();
161 
162           TySize *= CUI->getZExtValue();   // Get total allocated size.
163           if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
164           int FrameIndex = INT_MAX;
165           auto Iter = CatchObjects.find(AI);
166           if (Iter != CatchObjects.end() && TLI->needsFixedCatchObjects()) {
167             FrameIndex = MF->getFrameInfo().CreateFixedObject(
168                 TySize, 0, /*IsImmutable=*/false, /*isAliased=*/true);
169             MF->getFrameInfo().setObjectAlignment(FrameIndex, Alignment);
170           } else {
171             FrameIndex = MF->getFrameInfo().CreateStackObject(TySize, Alignment,
172                                                               false, AI);
173           }
174 
175           // Scalable vectors may need a special StackID to distinguish
176           // them from other (fixed size) stack objects.
177           if (isa<ScalableVectorType>(Ty))
178             MF->getFrameInfo().setStackID(FrameIndex,
179                                           TFI->getStackIDForScalableVectors());
180 
181           StaticAllocaMap[AI] = FrameIndex;
182           // Update the catch handler information.
183           if (Iter != CatchObjects.end()) {
184             for (int *CatchObjPtr : Iter->second)
185               *CatchObjPtr = FrameIndex;
186           }
187         } else {
188           // FIXME: Overaligned static allocas should be grouped into
189           // a single dynamic allocation instead of using a separate
190           // stack allocation for each one.
191           // Inform the Frame Information that we have variable-sized objects.
192           MF->getFrameInfo().CreateVariableSizedObject(
193               Alignment <= StackAlign ? Align(1) : Alignment, AI);
194         }
195       } else if (auto *Call = dyn_cast<CallBase>(&I)) {
196         // Look for inline asm that clobbers the SP register.
197         if (Call->isInlineAsm()) {
198           Register SP = TLI->getStackPointerRegisterToSaveRestore();
199           const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
200           std::vector<TargetLowering::AsmOperandInfo> Ops =
201               TLI->ParseConstraints(Fn->getParent()->getDataLayout(), TRI,
202                                     *Call);
203           for (TargetLowering::AsmOperandInfo &Op : Ops) {
204             if (Op.Type == InlineAsm::isClobber) {
205               // Clobbers don't have SDValue operands, hence SDValue().
206               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
207               std::pair<unsigned, const TargetRegisterClass *> PhysReg =
208                   TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
209                                                     Op.ConstraintVT);
210               if (PhysReg.first == SP)
211                 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
212             }
213           }
214         }
215         // Look for calls to the @llvm.va_start intrinsic. We can omit some
216         // prologue boilerplate for variadic functions that don't examine their
217         // arguments.
218         if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
219           if (II->getIntrinsicID() == Intrinsic::vastart)
220             MF->getFrameInfo().setHasVAStart(true);
221         }
222 
223         // If we have a musttail call in a variadic function, we need to ensure
224         // we forward implicit register parameters.
225         if (const auto *CI = dyn_cast<CallInst>(&I)) {
226           if (CI->isMustTailCall() && Fn->isVarArg())
227             MF->getFrameInfo().setHasMustTailInVarArgFunc(true);
228         }
229       }
230 
231       // Mark values used outside their block as exported, by allocating
232       // a virtual register for them.
233       if (isUsedOutsideOfDefiningBlock(&I))
234         if (!isa<AllocaInst>(I) || !StaticAllocaMap.count(cast<AllocaInst>(&I)))
235           InitializeRegForValue(&I);
236 
237       // Decide the preferred extend type for a value.
238       PreferredExtendType[&I] = getPreferredExtendForValue(&I);
239     }
240   }
241 
242   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
243   // also creates the initial PHI MachineInstrs, though none of the input
244   // operands are populated.
245   for (const BasicBlock &BB : *Fn) {
246     // Don't create MachineBasicBlocks for imaginary EH pad blocks. These blocks
247     // are really data, and no instructions can live here.
248     if (BB.isEHPad()) {
249       const Instruction *PadInst = BB.getFirstNonPHI();
250       // If this is a non-landingpad EH pad, mark this function as using
251       // funclets.
252       // FIXME: SEH catchpads do not create EH scope/funclets, so we could avoid
253       // setting this in such cases in order to improve frame layout.
254       if (!isa<LandingPadInst>(PadInst)) {
255         MF->setHasEHScopes(true);
256         MF->setHasEHFunclets(true);
257         MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
258       }
259       if (isa<CatchSwitchInst>(PadInst)) {
260         assert(&*BB.begin() == PadInst &&
261                "WinEHPrepare failed to remove PHIs from imaginary BBs");
262         continue;
263       }
264       if (isa<FuncletPadInst>(PadInst))
265         assert(&*BB.begin() == PadInst && "WinEHPrepare failed to demote PHIs");
266     }
267 
268     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(&BB);
269     MBBMap[&BB] = MBB;
270     MF->push_back(MBB);
271 
272     // Transfer the address-taken flag. This is necessary because there could
273     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
274     // the first one should be marked.
275     if (BB.hasAddressTaken())
276       MBB->setHasAddressTaken();
277 
278     // Mark landing pad blocks.
279     if (BB.isEHPad())
280       MBB->setIsEHPad();
281 
282     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
283     // appropriate.
284     for (const PHINode &PN : BB.phis()) {
285       if (PN.use_empty())
286         continue;
287 
288       // Skip empty types
289       if (PN.getType()->isEmptyTy())
290         continue;
291 
292       DebugLoc DL = PN.getDebugLoc();
293       unsigned PHIReg = ValueMap[&PN];
294       assert(PHIReg && "PHI node does not have an assigned virtual register!");
295 
296       SmallVector<EVT, 4> ValueVTs;
297       ComputeValueVTs(*TLI, MF->getDataLayout(), PN.getType(), ValueVTs);
298       for (EVT VT : ValueVTs) {
299         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
300         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
301         for (unsigned i = 0; i != NumRegisters; ++i)
302           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
303         PHIReg += NumRegisters;
304       }
305     }
306   }
307 
308   if (isFuncletEHPersonality(Personality)) {
309     WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
310 
311     // Map all BB references in the WinEH data to MBBs.
312     for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
313       for (WinEHHandlerType &H : TBME.HandlerArray) {
314         if (H.Handler)
315           H.Handler = MBBMap[H.Handler.get<const BasicBlock *>()];
316       }
317     }
318     for (CxxUnwindMapEntry &UME : EHInfo.CxxUnwindMap)
319       if (UME.Cleanup)
320         UME.Cleanup = MBBMap[UME.Cleanup.get<const BasicBlock *>()];
321     for (SEHUnwindMapEntry &UME : EHInfo.SEHUnwindMap) {
322       const auto *BB = UME.Handler.get<const BasicBlock *>();
323       UME.Handler = MBBMap[BB];
324     }
325     for (ClrEHUnwindMapEntry &CME : EHInfo.ClrEHUnwindMap) {
326       const auto *BB = CME.Handler.get<const BasicBlock *>();
327       CME.Handler = MBBMap[BB];
328     }
329   }
330 
331   else if (Personality == EHPersonality::Wasm_CXX) {
332     WasmEHFuncInfo &EHInfo = *MF->getWasmEHFuncInfo();
333     // Map all BB references in the Wasm EH data to MBBs.
334     DenseMap<BBOrMBB, BBOrMBB> SrcToUnwindDest;
335     for (auto &KV : EHInfo.SrcToUnwindDest) {
336       const auto *Src = KV.first.get<const BasicBlock *>();
337       const auto *Dest = KV.second.get<const BasicBlock *>();
338       SrcToUnwindDest[MBBMap[Src]] = MBBMap[Dest];
339     }
340     EHInfo.SrcToUnwindDest = std::move(SrcToUnwindDest);
341     DenseMap<BBOrMBB, SmallPtrSet<BBOrMBB, 4>> UnwindDestToSrcs;
342     for (auto &KV : EHInfo.UnwindDestToSrcs) {
343       const auto *Dest = KV.first.get<const BasicBlock *>();
344       UnwindDestToSrcs[MBBMap[Dest]] = SmallPtrSet<BBOrMBB, 4>();
345       for (const auto P : KV.second)
346         UnwindDestToSrcs[MBBMap[Dest]].insert(
347             MBBMap[P.get<const BasicBlock *>()]);
348     }
349     EHInfo.UnwindDestToSrcs = std::move(UnwindDestToSrcs);
350   }
351 }
352 
353 /// clear - Clear out all the function-specific state. This returns this
354 /// FunctionLoweringInfo to an empty state, ready to be used for a
355 /// different function.
clear()356 void FunctionLoweringInfo::clear() {
357   MBBMap.clear();
358   ValueMap.clear();
359   VirtReg2Value.clear();
360   StaticAllocaMap.clear();
361   LiveOutRegInfo.clear();
362   VisitedBBs.clear();
363   ArgDbgValues.clear();
364   DescribedArgs.clear();
365   ByValArgFrameIndexMap.clear();
366   RegFixups.clear();
367   RegsWithFixups.clear();
368   StatepointStackSlots.clear();
369   StatepointRelocationMaps.clear();
370   PreferredExtendType.clear();
371 }
372 
373 /// CreateReg - Allocate a single virtual register for the given type.
CreateReg(MVT VT,bool isDivergent)374 Register FunctionLoweringInfo::CreateReg(MVT VT, bool isDivergent) {
375   return RegInfo->createVirtualRegister(
376       MF->getSubtarget().getTargetLowering()->getRegClassFor(VT, isDivergent));
377 }
378 
379 /// CreateRegs - Allocate the appropriate number of virtual registers of
380 /// the correctly promoted or expanded types.  Assign these registers
381 /// consecutive vreg numbers and return the first assigned number.
382 ///
383 /// In the case that the given value has struct or array type, this function
384 /// will assign registers for each member or element.
385 ///
CreateRegs(Type * Ty,bool isDivergent)386 Register FunctionLoweringInfo::CreateRegs(Type *Ty, bool isDivergent) {
387   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
388 
389   SmallVector<EVT, 4> ValueVTs;
390   ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
391 
392   Register FirstReg;
393   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
394     EVT ValueVT = ValueVTs[Value];
395     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
396 
397     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
398     for (unsigned i = 0; i != NumRegs; ++i) {
399       Register R = CreateReg(RegisterVT, isDivergent);
400       if (!FirstReg) FirstReg = R;
401     }
402   }
403   return FirstReg;
404 }
405 
CreateRegs(const Value * V)406 Register FunctionLoweringInfo::CreateRegs(const Value *V) {
407   return CreateRegs(V->getType(), DA && DA->isDivergent(V) &&
408                     !TLI->requiresUniformRegister(*MF, V));
409 }
410 
411 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
412 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
413 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
414 /// the larger bit width by zero extension. The bit width must be no smaller
415 /// than the LiveOutInfo's existing bit width.
416 const FunctionLoweringInfo::LiveOutInfo *
GetLiveOutRegInfo(Register Reg,unsigned BitWidth)417 FunctionLoweringInfo::GetLiveOutRegInfo(Register Reg, unsigned BitWidth) {
418   if (!LiveOutRegInfo.inBounds(Reg))
419     return nullptr;
420 
421   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
422   if (!LOI->IsValid)
423     return nullptr;
424 
425   if (BitWidth > LOI->Known.getBitWidth()) {
426     LOI->NumSignBits = 1;
427     LOI->Known = LOI->Known.anyext(BitWidth);
428   }
429 
430   return LOI;
431 }
432 
433 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
434 /// register based on the LiveOutInfo of its operands.
ComputePHILiveOutRegInfo(const PHINode * PN)435 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
436   Type *Ty = PN->getType();
437   if (!Ty->isIntegerTy() || Ty->isVectorTy())
438     return;
439 
440   SmallVector<EVT, 1> ValueVTs;
441   ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
442   assert(ValueVTs.size() == 1 &&
443          "PHIs with non-vector integer types should have a single VT.");
444   EVT IntVT = ValueVTs[0];
445 
446   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
447     return;
448   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
449   unsigned BitWidth = IntVT.getSizeInBits();
450 
451   Register DestReg = ValueMap[PN];
452   if (!Register::isVirtualRegister(DestReg))
453     return;
454   LiveOutRegInfo.grow(DestReg);
455   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
456 
457   Value *V = PN->getIncomingValue(0);
458   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
459     DestLOI.NumSignBits = 1;
460     DestLOI.Known = KnownBits(BitWidth);
461     return;
462   }
463 
464   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
465     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
466     DestLOI.NumSignBits = Val.getNumSignBits();
467     DestLOI.Known = KnownBits::makeConstant(Val);
468   } else {
469     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
470                                 "CopyToReg node was created.");
471     Register SrcReg = ValueMap[V];
472     if (!Register::isVirtualRegister(SrcReg)) {
473       DestLOI.IsValid = false;
474       return;
475     }
476     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
477     if (!SrcLOI) {
478       DestLOI.IsValid = false;
479       return;
480     }
481     DestLOI = *SrcLOI;
482   }
483 
484   assert(DestLOI.Known.Zero.getBitWidth() == BitWidth &&
485          DestLOI.Known.One.getBitWidth() == BitWidth &&
486          "Masks should have the same bit width as the type.");
487 
488   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
489     Value *V = PN->getIncomingValue(i);
490     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
491       DestLOI.NumSignBits = 1;
492       DestLOI.Known = KnownBits(BitWidth);
493       return;
494     }
495 
496     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
497       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
498       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
499       DestLOI.Known.Zero &= ~Val;
500       DestLOI.Known.One &= Val;
501       continue;
502     }
503 
504     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
505                                 "its CopyToReg node was created.");
506     Register SrcReg = ValueMap[V];
507     if (!SrcReg.isVirtual()) {
508       DestLOI.IsValid = false;
509       return;
510     }
511     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
512     if (!SrcLOI) {
513       DestLOI.IsValid = false;
514       return;
515     }
516     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
517     DestLOI.Known = KnownBits::commonBits(DestLOI.Known, SrcLOI->Known);
518   }
519 }
520 
521 /// setArgumentFrameIndex - Record frame index for the byval
522 /// argument. This overrides previous frame index entry for this argument,
523 /// if any.
setArgumentFrameIndex(const Argument * A,int FI)524 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
525                                                  int FI) {
526   ByValArgFrameIndexMap[A] = FI;
527 }
528 
529 /// getArgumentFrameIndex - Get frame index for the byval argument.
530 /// If the argument does not have any assigned frame index then 0 is
531 /// returned.
getArgumentFrameIndex(const Argument * A)532 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
533   auto I = ByValArgFrameIndexMap.find(A);
534   if (I != ByValArgFrameIndexMap.end())
535     return I->second;
536   LLVM_DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
537   return INT_MAX;
538 }
539 
getCatchPadExceptionPointerVReg(const Value * CPI,const TargetRegisterClass * RC)540 Register FunctionLoweringInfo::getCatchPadExceptionPointerVReg(
541     const Value *CPI, const TargetRegisterClass *RC) {
542   MachineRegisterInfo &MRI = MF->getRegInfo();
543   auto I = CatchPadExceptionPointers.insert({CPI, 0});
544   Register &VReg = I.first->second;
545   if (I.second)
546     VReg = MRI.createVirtualRegister(RC);
547   assert(VReg && "null vreg in exception pointer table!");
548   return VReg;
549 }
550 
551 const Value *
getValueFromVirtualReg(Register Vreg)552 FunctionLoweringInfo::getValueFromVirtualReg(Register Vreg) {
553   if (VirtReg2Value.empty()) {
554     SmallVector<EVT, 4> ValueVTs;
555     for (auto &P : ValueMap) {
556       ValueVTs.clear();
557       ComputeValueVTs(*TLI, Fn->getParent()->getDataLayout(),
558                       P.first->getType(), ValueVTs);
559       unsigned Reg = P.second;
560       for (EVT VT : ValueVTs) {
561         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
562         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
563           VirtReg2Value[Reg++] = P.first;
564       }
565     }
566   }
567   return VirtReg2Value.lookup(Vreg);
568 }
569