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