[WinEH] Push unique_ptr through the Action interface.
[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 namespace {
84 struct WinEHNumbering {
85   WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
86       CurrentBaseState(-1), NextState(0) {}
87
88   WinEHFuncInfo &FuncInfo;
89   int CurrentBaseState;
90   int NextState;
91
92   SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
93   SmallPtrSet<const Function *, 4> VisitedHandlers;
94
95   int currentEHNumber() const {
96     return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
97   }
98
99   void createUnwindMapEntry(int ToState, ActionHandler *AH);
100   void createTryBlockMapEntry(int TryLow, int TryHigh,
101                               ArrayRef<CatchHandler *> Handlers);
102   void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
103                        ImmutableCallSite CS);
104   void calculateStateNumbers(const Function &F);
105 };
106 }
107
108 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
109                                SelectionDAG *DAG) {
110   Fn = &fn;
111   MF = &mf;
112   TLI = MF->getSubtarget().getTargetLowering();
113   RegInfo = &MF->getRegInfo();
114   MachineModuleInfo &MMI = MF->getMMI();
115
116   // Check whether the function can return without sret-demotion.
117   SmallVector<ISD::OutputArg, 4> Outs;
118   GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
119   CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
120                                        Fn->isVarArg(), Outs, Fn->getContext());
121
122   // Initialize the mapping of values to registers.  This is only set up for
123   // instruction values that are used outside of the block that defines
124   // them.
125   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
126   for (; BB != EB; ++BB)
127     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
128          I != E; ++I) {
129       if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
130         // Static allocas can be folded into the initial stack frame adjustment.
131         if (AI->isStaticAlloca()) {
132           const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
133           Type *Ty = AI->getAllocatedType();
134           uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
135           unsigned Align =
136               std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
137                        AI->getAlignment());
138
139           TySize *= CUI->getZExtValue();   // Get total allocated size.
140           if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
141
142           StaticAllocaMap[AI] =
143             MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
144
145         } else {
146           unsigned Align = std::max(
147               (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
148                 AI->getAllocatedType()),
149               AI->getAlignment());
150           unsigned StackAlign =
151               MF->getSubtarget().getFrameLowering()->getStackAlignment();
152           if (Align <= StackAlign)
153             Align = 0;
154           // Inform the Frame Information that we have variable-sized objects.
155           MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
156         }
157       }
158
159       // Look for inline asm that clobbers the SP register.
160       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
161         ImmutableCallSite CS(I);
162         if (isa<InlineAsm>(CS.getCalledValue())) {
163           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
164           const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
165           std::vector<TargetLowering::AsmOperandInfo> Ops =
166               TLI->ParseConstraints(TRI, CS);
167           for (size_t I = 0, E = Ops.size(); I != E; ++I) {
168             TargetLowering::AsmOperandInfo &Op = Ops[I];
169             if (Op.Type == InlineAsm::isClobber) {
170               // Clobbers don't have SDValue operands, hence SDValue().
171               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
172               std::pair<unsigned, const TargetRegisterClass *> PhysReg =
173                   TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
174                                                     Op.ConstraintVT);
175               if (PhysReg.first == SP)
176                 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
177             }
178           }
179         }
180       }
181
182       // Look for calls to the @llvm.va_start intrinsic. We can omit some
183       // prologue boilerplate for variadic functions that don't examine their
184       // arguments.
185       if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
186         if (II->getIntrinsicID() == Intrinsic::vastart)
187           MF->getFrameInfo()->setHasVAStart(true);
188       }
189
190       // If we have a musttail call in a variadic funciton, we need to ensure we
191       // forward implicit register parameters.
192       if (const auto *CI = dyn_cast<CallInst>(I)) {
193         if (CI->isMustTailCall() && Fn->isVarArg())
194           MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
195       }
196
197       // Mark values used outside their block as exported, by allocating
198       // a virtual register for them.
199       if (isUsedOutsideOfDefiningBlock(I))
200         if (!isa<AllocaInst>(I) ||
201             !StaticAllocaMap.count(cast<AllocaInst>(I)))
202           InitializeRegForValue(I);
203
204       // Collect llvm.dbg.declare information. This is done now instead of
205       // during the initial isel pass through the IR so that it is done
206       // in a predictable order.
207       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
208         assert(DI->getVariable() && "Missing variable");
209         assert(DI->getDebugLoc() && "Missing location");
210         if (MMI.hasDebugInfo()) {
211           // Don't handle byval struct arguments or VLAs, for example.
212           // Non-byval arguments are handled here (they refer to the stack
213           // temporary alloca at this point).
214           const Value *Address = DI->getAddress();
215           if (Address) {
216             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
217               Address = BCI->getOperand(0);
218             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
219               DenseMap<const AllocaInst *, int>::iterator SI =
220                 StaticAllocaMap.find(AI);
221               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
222                 int FI = SI->second;
223                 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
224                                        FI, DI->getDebugLoc());
225               }
226             }
227           }
228         }
229       }
230
231       // Decide the preferred extend type for a value.
232       PreferredExtendType[I] = getPreferredExtendForValue(I);
233     }
234
235   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
236   // also creates the initial PHI MachineInstrs, though none of the input
237   // operands are populated.
238   for (BB = Fn->begin(); BB != EB; ++BB) {
239     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
240     MBBMap[BB] = MBB;
241     MF->push_back(MBB);
242
243     // Transfer the address-taken flag. This is necessary because there could
244     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
245     // the first one should be marked.
246     if (BB->hasAddressTaken())
247       MBB->setHasAddressTaken();
248
249     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
250     // appropriate.
251     for (BasicBlock::const_iterator I = BB->begin();
252          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
253       if (PN->use_empty()) continue;
254
255       // Skip empty types
256       if (PN->getType()->isEmptyTy())
257         continue;
258
259       DebugLoc DL = PN->getDebugLoc();
260       unsigned PHIReg = ValueMap[PN];
261       assert(PHIReg && "PHI node does not have an assigned virtual register!");
262
263       SmallVector<EVT, 4> ValueVTs;
264       ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
265       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
266         EVT VT = ValueVTs[vti];
267         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
268         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
269         for (unsigned i = 0; i != NumRegisters; ++i)
270           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
271         PHIReg += NumRegisters;
272       }
273     }
274   }
275
276   // Mark landing pad blocks.
277   SmallVector<const LandingPadInst *, 4> LPads;
278   for (BB = Fn->begin(); BB != EB; ++BB) {
279     if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
280       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
281     if (BB->isLandingPad())
282       LPads.push_back(BB->getLandingPadInst());
283   }
284
285   // If this is an MSVC EH personality, we need to do a bit more work.
286   EHPersonality Personality = EHPersonality::Unknown;
287   if (!LPads.empty())
288     Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
289   if (!isMSVCEHPersonality(Personality))
290     return;
291
292   WinEHFuncInfo *EHInfo = nullptr;
293   if (Personality == EHPersonality::MSVC_Win64SEH) {
294     addSEHHandlersForLPads(LPads);
295   } else if (Personality == EHPersonality::MSVC_CXX) {
296     const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
297     EHInfo = &MMI.getWinEHFuncInfo(WinEHParentFn);
298     if (EHInfo->LandingPadStateMap.empty()) {
299       WinEHNumbering Num(*EHInfo);
300       Num.calculateStateNumbers(*WinEHParentFn);
301       // Pop everything on the handler stack.
302       Num.processCallSite(None, ImmutableCallSite());
303     }
304
305     // Copy the state numbers to LandingPadInfo for the current function, which
306     // could be a handler or the parent.
307     for (const LandingPadInst *LP : LPads) {
308       MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
309       MMI.addWinEHState(LPadMBB, EHInfo->LandingPadStateMap[LP]);
310     }
311   }
312 }
313
314 void FunctionLoweringInfo::addSEHHandlersForLPads(
315     ArrayRef<const LandingPadInst *> LPads) {
316   MachineModuleInfo &MMI = MF->getMMI();
317
318   // Iterate over all landing pads with llvm.eh.actions calls.
319   for (const LandingPadInst *LP : LPads) {
320     const IntrinsicInst *ActionsCall =
321         dyn_cast<IntrinsicInst>(LP->getNextNode());
322     if (!ActionsCall ||
323         ActionsCall->getIntrinsicID() != Intrinsic::eh_actions)
324       continue;
325
326     // Parse the llvm.eh.actions call we found.
327     MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
328     SmallVector<std::unique_ptr<ActionHandler>, 4> Actions;
329     parseEHActions(ActionsCall, Actions);
330
331     // Iterate EH actions from most to least precedence, which means
332     // iterating in reverse.
333     for (auto I = Actions.rbegin(), E = Actions.rend(); I != E; ++I) {
334       ActionHandler *Action = I->get();
335       if (auto *CH = dyn_cast<CatchHandler>(Action)) {
336         const auto *Filter =
337             dyn_cast<Function>(CH->getSelector()->stripPointerCasts());
338         assert((Filter || CH->getSelector()->isNullValue()) &&
339                "expected function or catch-all");
340         const auto *RecoverBA =
341             cast<BlockAddress>(CH->getHandlerBlockOrFunc());
342         MMI.addSEHCatchHandler(LPadMBB, Filter, RecoverBA);
343       } else {
344         assert(isa<CleanupHandler>(Action));
345         const auto *Fini = cast<Function>(Action->getHandlerBlockOrFunc());
346         MMI.addSEHCleanupHandler(LPadMBB, Fini);
347       }
348     }
349   }
350 }
351
352 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
353   WinEHUnwindMapEntry UME;
354   UME.ToState = ToState;
355   if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
356     UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
357   else
358     UME.Cleanup = nullptr;
359   FuncInfo.UnwindMap.push_back(UME);
360 }
361
362 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
363                                             ArrayRef<CatchHandler *> Handlers) {
364   WinEHTryBlockMapEntry TBME;
365   TBME.TryLow = TryLow;
366   TBME.TryHigh = TryHigh;
367   assert(TBME.TryLow <= TBME.TryHigh);
368   for (CatchHandler *CH : Handlers) {
369     WinEHHandlerType HT;
370     if (CH->getSelector()->isNullValue()) {
371       HT.Adjectives = 0x40;
372       HT.TypeDescriptor = nullptr;
373     } else {
374       auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
375       // Selectors are always pointers to GlobalVariables with 'struct' type.
376       // The struct has two fields, adjectives and a type descriptor.
377       auto *CS = cast<ConstantStruct>(GV->getInitializer());
378       HT.Adjectives =
379           cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
380       HT.TypeDescriptor =
381           cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
382     }
383     HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
384     HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
385     TBME.HandlerArray.push_back(HT);
386   }
387   FuncInfo.TryBlockMap.push_back(TBME);
388 }
389
390 static void print_name(const Value *V) {
391 #ifndef NDEBUG
392   if (!V) {
393     DEBUG(dbgs() << "null");
394     return;
395   }
396
397   if (const auto *F = dyn_cast<Function>(V))
398     DEBUG(dbgs() << F->getName());
399   else
400     DEBUG(V->dump());
401 #endif
402 }
403
404 void WinEHNumbering::processCallSite(
405     MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
406     ImmutableCallSite CS) {
407   DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
408                << ") for: ");
409   print_name(CS ? CS.getCalledValue() : nullptr);
410   DEBUG(dbgs() << '\n');
411
412   DEBUG(dbgs() << "HandlerStack: \n");
413   for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
414     DEBUG(dbgs() << "  ");
415     print_name(HandlerStack[I]->getHandlerBlockOrFunc());
416     DEBUG(dbgs() << '\n');
417   }
418   DEBUG(dbgs() << "Actions: \n");
419   for (int I = 0, E = Actions.size(); I < E; ++I) {
420     DEBUG(dbgs() << "  ");
421     print_name(Actions[I]->getHandlerBlockOrFunc());
422     DEBUG(dbgs() << '\n');
423   }
424   int FirstMismatch = 0;
425   for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
426        ++FirstMismatch) {
427     if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
428         Actions[FirstMismatch]->getHandlerBlockOrFunc())
429       break;
430   }
431
432   // Don't recurse while we are looping over the handler stack.  Instead, defer
433   // the numbering of the catch handlers until we are done popping.
434   SmallVector<CatchHandler *, 4> PoppedCatches;
435   for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
436     std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
437     if (isa<CatchHandler>(Handler.get()))
438       PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
439   }
440
441   int TryHigh = NextState - 1;
442   int LastTryLowIdx = 0;
443   for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
444     CatchHandler *CH = PoppedCatches[I];
445     DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
446     if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
447       int TryLow = CH->getEHState();
448       auto Handlers =
449           makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
450       DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
451       for (size_t J = 0; J < Handlers.size(); ++J) {
452         DEBUG(dbgs() << ", ");
453         print_name(Handlers[J]->getHandlerBlockOrFunc());
454       }
455       DEBUG(dbgs() << ")\n");
456       createTryBlockMapEntry(TryLow, TryHigh, Handlers);
457       LastTryLowIdx = I + 1;
458     }
459   }
460
461   for (CatchHandler *CH : PoppedCatches) {
462     if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
463       DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
464       print_name(F);
465       DEBUG(dbgs() << '\n');
466       FuncInfo.HandlerBaseState[F] = NextState;
467       DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() 
468                    << ", null)\n");
469       createUnwindMapEntry(currentEHNumber(), nullptr);
470       ++NextState;
471       calculateStateNumbers(*F);
472     }
473     delete CH;
474   }
475
476   // The handler functions may have pushed actions onto the handler stack
477   // that we expected to push here.  Compare the handler stack to our
478   // actions again to check for that possibility.
479   if (HandlerStack.size() > (size_t)FirstMismatch) {
480     for (int E = std::min(HandlerStack.size(), Actions.size());
481          FirstMismatch < E; ++FirstMismatch) {
482       if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
483           Actions[FirstMismatch]->getHandlerBlockOrFunc())
484         break;
485     }
486   }
487
488   DEBUG(dbgs() << "Pushing actions for CallSite: ");
489   print_name(CS ? CS.getCalledValue() : nullptr);
490   DEBUG(dbgs() << '\n');
491
492   bool LastActionWasCatch = false;
493   for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
494     // We can reuse eh states when pushing two catches for the same invoke.
495     bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
496     // FIXME: Reenable this optimization!
497     if (CurrActionIsCatch && LastActionWasCatch && false) {
498       DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber()
499                    << "\n");
500       Actions[I]->setEHState(currentEHNumber());
501     } else {
502       DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
503       print_name(Actions[I]->getHandlerBlockOrFunc());
504       DEBUG(dbgs() << ")\n");
505       createUnwindMapEntry(currentEHNumber(), Actions[I].get());
506       DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
507       Actions[I]->setEHState(NextState);
508       NextState++;
509     }
510     HandlerStack.push_back(std::move(Actions[I]));
511     LastActionWasCatch = CurrActionIsCatch;
512   }
513
514   DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
515   print_name(CS ? CS.getCalledValue() : nullptr);
516   DEBUG(dbgs() << '\n');
517 }
518
519 void WinEHNumbering::calculateStateNumbers(const Function &F) {
520   auto I = VisitedHandlers.insert(&F);
521   if (!I.second)
522     return; // We've already visited this handler, don't renumber it.
523
524   int OldBaseState = CurrentBaseState;
525   if (FuncInfo.HandlerBaseState.count(&F)) {
526     CurrentBaseState = FuncInfo.HandlerBaseState[&F];
527   }
528
529   DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
530   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
531   for (const BasicBlock &BB : F) {
532     for (const Instruction &I : BB) {
533       const auto *CI = dyn_cast<CallInst>(&I);
534       if (!CI || CI->doesNotThrow())
535         continue;
536       processCallSite(None, CI);
537     }
538     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
539     if (!II)
540       continue;
541     const LandingPadInst *LPI = II->getLandingPadInst();
542     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
543     if (!ActionsCall)
544       continue;
545     assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
546     parseEHActions(ActionsCall, ActionList);
547     if (ActionList.empty())
548       continue;
549     processCallSite(ActionList, II);
550     ActionList.clear();
551     FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
552     DEBUG(dbgs() << "Assigning state " << currentEHNumber()
553                   << " to landing pad at " << LPI->getParent()->getName()
554                   << '\n');
555   }
556
557   FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
558
559   CurrentBaseState = OldBaseState;
560 }
561
562 /// clear - Clear out all the function-specific state. This returns this
563 /// FunctionLoweringInfo to an empty state, ready to be used for a
564 /// different function.
565 void FunctionLoweringInfo::clear() {
566   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
567          "Not all catch info was assigned to a landing pad!");
568
569   MBBMap.clear();
570   ValueMap.clear();
571   StaticAllocaMap.clear();
572 #ifndef NDEBUG
573   CatchInfoLost.clear();
574   CatchInfoFound.clear();
575 #endif
576   LiveOutRegInfo.clear();
577   VisitedBBs.clear();
578   ArgDbgValues.clear();
579   ByValArgFrameIndexMap.clear();
580   RegFixups.clear();
581   StatepointStackSlots.clear();
582   PreferredExtendType.clear();
583 }
584
585 /// CreateReg - Allocate a single virtual register for the given type.
586 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
587   return RegInfo->createVirtualRegister(
588       MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
589 }
590
591 /// CreateRegs - Allocate the appropriate number of virtual registers of
592 /// the correctly promoted or expanded types.  Assign these registers
593 /// consecutive vreg numbers and return the first assigned number.
594 ///
595 /// In the case that the given value has struct or array type, this function
596 /// will assign registers for each member or element.
597 ///
598 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
599   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
600
601   SmallVector<EVT, 4> ValueVTs;
602   ComputeValueVTs(*TLI, Ty, ValueVTs);
603
604   unsigned FirstReg = 0;
605   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
606     EVT ValueVT = ValueVTs[Value];
607     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
608
609     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
610     for (unsigned i = 0; i != NumRegs; ++i) {
611       unsigned R = CreateReg(RegisterVT);
612       if (!FirstReg) FirstReg = R;
613     }
614   }
615   return FirstReg;
616 }
617
618 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
619 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
620 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
621 /// the larger bit width by zero extension. The bit width must be no smaller
622 /// than the LiveOutInfo's existing bit width.
623 const FunctionLoweringInfo::LiveOutInfo *
624 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
625   if (!LiveOutRegInfo.inBounds(Reg))
626     return nullptr;
627
628   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
629   if (!LOI->IsValid)
630     return nullptr;
631
632   if (BitWidth > LOI->KnownZero.getBitWidth()) {
633     LOI->NumSignBits = 1;
634     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
635     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
636   }
637
638   return LOI;
639 }
640
641 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
642 /// register based on the LiveOutInfo of its operands.
643 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
644   Type *Ty = PN->getType();
645   if (!Ty->isIntegerTy() || Ty->isVectorTy())
646     return;
647
648   SmallVector<EVT, 1> ValueVTs;
649   ComputeValueVTs(*TLI, Ty, ValueVTs);
650   assert(ValueVTs.size() == 1 &&
651          "PHIs with non-vector integer types should have a single VT.");
652   EVT IntVT = ValueVTs[0];
653
654   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
655     return;
656   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
657   unsigned BitWidth = IntVT.getSizeInBits();
658
659   unsigned DestReg = ValueMap[PN];
660   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
661     return;
662   LiveOutRegInfo.grow(DestReg);
663   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
664
665   Value *V = PN->getIncomingValue(0);
666   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
667     DestLOI.NumSignBits = 1;
668     APInt Zero(BitWidth, 0);
669     DestLOI.KnownZero = Zero;
670     DestLOI.KnownOne = Zero;
671     return;
672   }
673
674   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
675     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
676     DestLOI.NumSignBits = Val.getNumSignBits();
677     DestLOI.KnownZero = ~Val;
678     DestLOI.KnownOne = Val;
679   } else {
680     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
681                                 "CopyToReg node was created.");
682     unsigned SrcReg = ValueMap[V];
683     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
684       DestLOI.IsValid = false;
685       return;
686     }
687     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
688     if (!SrcLOI) {
689       DestLOI.IsValid = false;
690       return;
691     }
692     DestLOI = *SrcLOI;
693   }
694
695   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
696          DestLOI.KnownOne.getBitWidth() == BitWidth &&
697          "Masks should have the same bit width as the type.");
698
699   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
700     Value *V = PN->getIncomingValue(i);
701     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
702       DestLOI.NumSignBits = 1;
703       APInt Zero(BitWidth, 0);
704       DestLOI.KnownZero = Zero;
705       DestLOI.KnownOne = Zero;
706       return;
707     }
708
709     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
710       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
711       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
712       DestLOI.KnownZero &= ~Val;
713       DestLOI.KnownOne &= Val;
714       continue;
715     }
716
717     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
718                                 "its CopyToReg node was created.");
719     unsigned SrcReg = ValueMap[V];
720     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
721       DestLOI.IsValid = false;
722       return;
723     }
724     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
725     if (!SrcLOI) {
726       DestLOI.IsValid = false;
727       return;
728     }
729     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
730     DestLOI.KnownZero &= SrcLOI->KnownZero;
731     DestLOI.KnownOne &= SrcLOI->KnownOne;
732   }
733 }
734
735 /// setArgumentFrameIndex - Record frame index for the byval
736 /// argument. This overrides previous frame index entry for this argument,
737 /// if any.
738 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
739                                                  int FI) {
740   ByValArgFrameIndexMap[A] = FI;
741 }
742
743 /// getArgumentFrameIndex - Get frame index for the byval argument.
744 /// If the argument does not have any assigned frame index then 0 is
745 /// returned.
746 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
747   DenseMap<const Argument *, int>::iterator I =
748     ByValArgFrameIndexMap.find(A);
749   if (I != ByValArgFrameIndexMap.end())
750     return I->second;
751   DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
752   return 0;
753 }
754
755 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
756 /// being passed to this variadic function, and set the MachineModuleInfo's
757 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
758 /// reference to _fltused on Windows, which will link in MSVCRT's
759 /// floating-point support.
760 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
761                                       MachineModuleInfo *MMI)
762 {
763   FunctionType *FT = cast<FunctionType>(
764     I.getCalledValue()->getType()->getContainedType(0));
765   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
766     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
767       Type* T = I.getArgOperand(i)->getType();
768       for (auto i : post_order(T)) {
769         if (i->isFloatingPointTy()) {
770           MMI->setUsesVAFloatArgument(true);
771           return;
772         }
773       }
774     }
775   }
776 }
777
778 /// AddLandingPadInfo - Extract the exception handling information from the
779 /// landingpad instruction and add them to the specified machine module info.
780 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
781                              MachineBasicBlock *MBB) {
782   MMI.addPersonality(MBB,
783                      cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
784
785   if (I.isCleanup())
786     MMI.addCleanup(MBB);
787
788   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
789   //        but we need to do it this way because of how the DWARF EH emitter
790   //        processes the clauses.
791   for (unsigned i = I.getNumClauses(); i != 0; --i) {
792     Value *Val = I.getClause(i - 1);
793     if (I.isCatch(i - 1)) {
794       MMI.addCatchTypeInfo(MBB,
795                            dyn_cast<GlobalValue>(Val->stripPointerCasts()));
796     } else {
797       // Add filters in a list.
798       Constant *CVal = cast<Constant>(Val);
799       SmallVector<const GlobalValue*, 4> FilterList;
800       for (User::op_iterator
801              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
802         FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
803
804       MMI.addFilterTypeInfo(MBB, FilterList);
805     }
806   }
807 }