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