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