LLVM  mainline
FunctionLoweringInfo.cpp
Go to the documentation of this file.
00001 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements routines for translating functions from LLVM IR into
00011 // Machine IR.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00016 #include "llvm/ADT/PostOrderIterator.h"
00017 #include "llvm/CodeGen/Analysis.h"
00018 #include "llvm/CodeGen/MachineFrameInfo.h"
00019 #include "llvm/CodeGen/MachineFunction.h"
00020 #include "llvm/CodeGen/MachineInstrBuilder.h"
00021 #include "llvm/CodeGen/MachineModuleInfo.h"
00022 #include "llvm/CodeGen/MachineRegisterInfo.h"
00023 #include "llvm/CodeGen/WinEHFuncInfo.h"
00024 #include "llvm/IR/DataLayout.h"
00025 #include "llvm/IR/DebugInfo.h"
00026 #include "llvm/IR/DerivedTypes.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/IntrinsicInst.h"
00030 #include "llvm/IR/LLVMContext.h"
00031 #include "llvm/IR/Module.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include "llvm/Support/MathExtras.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetFrameLowering.h"
00037 #include "llvm/Target/TargetInstrInfo.h"
00038 #include "llvm/Target/TargetLowering.h"
00039 #include "llvm/Target/TargetOptions.h"
00040 #include "llvm/Target/TargetRegisterInfo.h"
00041 #include "llvm/Target/TargetSubtargetInfo.h"
00042 #include <algorithm>
00043 using namespace llvm;
00044 
00045 #define DEBUG_TYPE "function-lowering-info"
00046 
00047 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
00048 /// PHI nodes or outside of the basic block that defines it, or used by a
00049 /// switch or atomic instruction, which may expand to multiple basic blocks.
00050 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
00051   if (I->use_empty()) return false;
00052   if (isa<PHINode>(I)) return true;
00053   const BasicBlock *BB = I->getParent();
00054   for (const User *U : I->users())
00055     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
00056       return true;
00057 
00058   return false;
00059 }
00060 
00061 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
00062   // For the users of the source value being used for compare instruction, if
00063   // the number of signed predicate is greater than unsigned predicate, we
00064   // prefer to use SIGN_EXTEND.
00065   //
00066   // With this optimization, we would be able to reduce some redundant sign or
00067   // zero extension instruction, and eventually more machine CSE opportunities
00068   // can be exposed.
00069   ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
00070   unsigned NumOfSigned = 0, NumOfUnsigned = 0;
00071   for (const User *U : V->users()) {
00072     if (const auto *CI = dyn_cast<CmpInst>(U)) {
00073       NumOfSigned += CI->isSigned();
00074       NumOfUnsigned += CI->isUnsigned();
00075     }
00076   }
00077   if (NumOfSigned > NumOfUnsigned)
00078     ExtendKind = ISD::SIGN_EXTEND;
00079 
00080   return ExtendKind;
00081 }
00082 
00083 namespace {
00084 struct WinEHNumbering {
00085   WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo), NextState(0) {}
00086 
00087   WinEHFuncInfo &FuncInfo;
00088   int NextState;
00089 
00090   SmallVector<ActionHandler *, 4> HandlerStack;
00091   SmallPtrSet<const Function *, 4> VisitedHandlers;
00092 
00093   int currentEHNumber() const {
00094     return HandlerStack.empty() ? -1 : HandlerStack.back()->getEHState();
00095   }
00096 
00097   void createUnwindMapEntry(int ToState, ActionHandler *AH);
00098   void createTryBlockMapEntry(int TryLow, int TryHigh,
00099                               ArrayRef<CatchHandler *> Handlers);
00100   void processCallSite(ArrayRef<ActionHandler *> Actions, ImmutableCallSite CS);
00101   void calculateStateNumbers(const Function &F);
00102 };
00103 }
00104 
00105 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
00106                                SelectionDAG *DAG) {
00107   Fn = &fn;
00108   MF = &mf;
00109   TLI = MF->getSubtarget().getTargetLowering();
00110   RegInfo = &MF->getRegInfo();
00111   MachineModuleInfo &MMI = MF->getMMI();
00112 
00113   // Check whether the function can return without sret-demotion.
00114   SmallVector<ISD::OutputArg, 4> Outs;
00115   GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
00116   CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
00117                                        Fn->isVarArg(), Outs, Fn->getContext());
00118 
00119   // Initialize the mapping of values to registers.  This is only set up for
00120   // instruction values that are used outside of the block that defines
00121   // them.
00122   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
00123   for (; BB != EB; ++BB)
00124     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
00125          I != E; ++I) {
00126       if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
00127         // Static allocas can be folded into the initial stack frame adjustment.
00128         if (AI->isStaticAlloca()) {
00129           const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
00130           Type *Ty = AI->getAllocatedType();
00131           uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
00132           unsigned Align =
00133               std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
00134                        AI->getAlignment());
00135 
00136           TySize *= CUI->getZExtValue();   // Get total allocated size.
00137           if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
00138 
00139           StaticAllocaMap[AI] =
00140             MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
00141 
00142         } else {
00143           unsigned Align = std::max(
00144               (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
00145                 AI->getAllocatedType()),
00146               AI->getAlignment());
00147           unsigned StackAlign =
00148               MF->getSubtarget().getFrameLowering()->getStackAlignment();
00149           if (Align <= StackAlign)
00150             Align = 0;
00151           // Inform the Frame Information that we have variable-sized objects.
00152           MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
00153         }
00154       }
00155 
00156       // Look for inline asm that clobbers the SP register.
00157       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
00158         ImmutableCallSite CS(I);
00159         if (isa<InlineAsm>(CS.getCalledValue())) {
00160           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
00161           const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00162           std::vector<TargetLowering::AsmOperandInfo> Ops =
00163               TLI->ParseConstraints(TRI, CS);
00164           for (size_t I = 0, E = Ops.size(); I != E; ++I) {
00165             TargetLowering::AsmOperandInfo &Op = Ops[I];
00166             if (Op.Type == InlineAsm::isClobber) {
00167               // Clobbers don't have SDValue operands, hence SDValue().
00168               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
00169               std::pair<unsigned, const TargetRegisterClass *> PhysReg =
00170                   TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
00171                                                     Op.ConstraintVT);
00172               if (PhysReg.first == SP)
00173                 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
00174             }
00175           }
00176         }
00177       }
00178 
00179       // Look for calls to the @llvm.va_start intrinsic. We can omit some
00180       // prologue boilerplate for variadic functions that don't examine their
00181       // arguments.
00182       if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
00183         if (II->getIntrinsicID() == Intrinsic::vastart)
00184           MF->getFrameInfo()->setHasVAStart(true);
00185       }
00186 
00187       // If we have a musttail call in a variadic funciton, we need to ensure we
00188       // forward implicit register parameters.
00189       if (const auto *CI = dyn_cast<CallInst>(I)) {
00190         if (CI->isMustTailCall() && Fn->isVarArg())
00191           MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
00192       }
00193 
00194       // Mark values used outside their block as exported, by allocating
00195       // a virtual register for them.
00196       if (isUsedOutsideOfDefiningBlock(I))
00197         if (!isa<AllocaInst>(I) ||
00198             !StaticAllocaMap.count(cast<AllocaInst>(I)))
00199           InitializeRegForValue(I);
00200 
00201       // Collect llvm.dbg.declare information. This is done now instead of
00202       // during the initial isel pass through the IR so that it is done
00203       // in a predictable order.
00204       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
00205         DIVariable DIVar = DI->getVariable();
00206         if (MMI.hasDebugInfo() && DIVar && DI->getDebugLoc()) {
00207           // Don't handle byval struct arguments or VLAs, for example.
00208           // Non-byval arguments are handled here (they refer to the stack
00209           // temporary alloca at this point).
00210           const Value *Address = DI->getAddress();
00211           if (Address) {
00212             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
00213               Address = BCI->getOperand(0);
00214             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
00215               DenseMap<const AllocaInst *, int>::iterator SI =
00216                 StaticAllocaMap.find(AI);
00217               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
00218                 int FI = SI->second;
00219                 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
00220                                        FI, DI->getDebugLoc());
00221               }
00222             }
00223           }
00224         }
00225       }
00226 
00227       // Decide the preferred extend type for a value.
00228       PreferredExtendType[I] = getPreferredExtendForValue(I);
00229     }
00230 
00231   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
00232   // also creates the initial PHI MachineInstrs, though none of the input
00233   // operands are populated.
00234   for (BB = Fn->begin(); BB != EB; ++BB) {
00235     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
00236     MBBMap[BB] = MBB;
00237     MF->push_back(MBB);
00238 
00239     // Transfer the address-taken flag. This is necessary because there could
00240     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
00241     // the first one should be marked.
00242     if (BB->hasAddressTaken())
00243       MBB->setHasAddressTaken();
00244 
00245     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
00246     // appropriate.
00247     for (BasicBlock::const_iterator I = BB->begin();
00248          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
00249       if (PN->use_empty()) continue;
00250 
00251       // Skip empty types
00252       if (PN->getType()->isEmptyTy())
00253         continue;
00254 
00255       DebugLoc DL = PN->getDebugLoc();
00256       unsigned PHIReg = ValueMap[PN];
00257       assert(PHIReg && "PHI node does not have an assigned virtual register!");
00258 
00259       SmallVector<EVT, 4> ValueVTs;
00260       ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
00261       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
00262         EVT VT = ValueVTs[vti];
00263         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
00264         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00265         for (unsigned i = 0; i != NumRegisters; ++i)
00266           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
00267         PHIReg += NumRegisters;
00268       }
00269     }
00270   }
00271 
00272   // Mark landing pad blocks.
00273   for (BB = Fn->begin(); BB != EB; ++BB)
00274     if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
00275       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
00276 
00277   // Calculate EH numbers for WinEH.
00278   if (fn.hasFnAttribute("wineh-parent")) {
00279     const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
00280     WinEHFuncInfo &FI = MMI.getWinEHFuncInfo(WinEHParentFn);
00281     if (FI.LandingPadStateMap.empty()) {
00282       WinEHNumbering Num(FI);
00283       Num.calculateStateNumbers(*WinEHParentFn);
00284       // Pop everything on the handler stack.
00285       Num.processCallSite(None, ImmutableCallSite());
00286     }
00287   }
00288 }
00289 
00290 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
00291   WinEHUnwindMapEntry UME;
00292   UME.ToState = ToState;
00293   if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
00294     UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
00295   else
00296     UME.Cleanup = nullptr;
00297   FuncInfo.UnwindMap.push_back(UME);
00298 }
00299 
00300 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
00301                                             ArrayRef<CatchHandler *> Handlers) {
00302   WinEHTryBlockMapEntry TBME;
00303   TBME.TryLow = TryLow;
00304   TBME.TryHigh = TryHigh;
00305   assert(TBME.TryLow <= TBME.TryHigh);
00306   for (CatchHandler *CH : Handlers) {
00307     WinEHHandlerType HT;
00308     if (CH->getSelector()->isNullValue()) {
00309       HT.Adjectives = 0x40;
00310       HT.TypeDescriptor = nullptr;
00311     } else {
00312       auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
00313       // Selectors are always pointers to GlobalVariables with 'struct' type.
00314       // The struct has two fields, adjectives and a type descriptor.
00315       auto *CS = cast<ConstantStruct>(GV->getInitializer());
00316       HT.Adjectives =
00317           cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
00318       HT.TypeDescriptor =
00319           cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
00320     }
00321     HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
00322     HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
00323     TBME.HandlerArray.push_back(HT);
00324   }
00325   FuncInfo.TryBlockMap.push_back(TBME);
00326 }
00327 
00328 static void print_name(const Value *V) {
00329 #ifndef NDEBUG
00330   if (!V) {
00331     DEBUG(dbgs() << "null");
00332     return;
00333   }
00334 
00335   if (const auto *F = dyn_cast<Function>(V))
00336     DEBUG(dbgs() << F->getName());
00337   else
00338     DEBUG(V->dump());
00339 #endif
00340 }
00341 
00342 void WinEHNumbering::processCallSite(ArrayRef<ActionHandler *> Actions,
00343                                      ImmutableCallSite CS) {
00344   int FirstMismatch = 0;
00345   for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
00346        ++FirstMismatch) {
00347     if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
00348         Actions[FirstMismatch]->getHandlerBlockOrFunc())
00349       break;
00350     delete Actions[FirstMismatch];
00351   }
00352 
00353   bool EnteringScope = (int)Actions.size() > FirstMismatch;
00354 
00355   // Don't recurse while we are looping over the handler stack.  Instead, defer
00356   // the numbering of the catch handlers until we are done popping.
00357   SmallVector<CatchHandler *, 4> PoppedCatches;
00358   for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
00359     if (auto *CH = dyn_cast<CatchHandler>(HandlerStack.back())) {
00360       PoppedCatches.push_back(CH);
00361     } else {
00362       // Delete cleanup handlers
00363       delete HandlerStack.back();
00364     }
00365     HandlerStack.pop_back();
00366   }
00367 
00368   // We need to create a new state number if we are exiting a try scope and we
00369   // will not push any more actions.
00370   int TryHigh = NextState - 1;
00371   if (!EnteringScope && !PoppedCatches.empty()) {
00372     createUnwindMapEntry(currentEHNumber(), nullptr);
00373     ++NextState;
00374   }
00375 
00376   int LastTryLowIdx = 0;
00377   for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
00378     CatchHandler *CH = PoppedCatches[I];
00379     if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
00380       int TryLow = CH->getEHState();
00381       auto Handlers =
00382           makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
00383       createTryBlockMapEntry(TryLow, TryHigh, Handlers);
00384       LastTryLowIdx = I + 1;
00385     }
00386   }
00387 
00388   for (CatchHandler *CH : PoppedCatches) {
00389     if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc()))
00390       calculateStateNumbers(*F);
00391     delete CH;
00392   }
00393 
00394   bool LastActionWasCatch = false;
00395   for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
00396     // We can reuse eh states when pushing two catches for the same invoke.
00397     bool CurrActionIsCatch = isa<CatchHandler>(Actions[I]);
00398     // FIXME: Reenable this optimization!
00399     if (CurrActionIsCatch && LastActionWasCatch && false) {
00400       Actions[I]->setEHState(currentEHNumber());
00401     } else {
00402       createUnwindMapEntry(currentEHNumber(), Actions[I]);
00403       Actions[I]->setEHState(NextState);
00404       NextState++;
00405       DEBUG(dbgs() << "Creating unwind map entry for: (");
00406       print_name(Actions[I]->getHandlerBlockOrFunc());
00407       DEBUG(dbgs() << ", " << currentEHNumber() << ")\n");
00408     }
00409     HandlerStack.push_back(Actions[I]);
00410     LastActionWasCatch = CurrActionIsCatch;
00411   }
00412 
00413   DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
00414   print_name(CS ? CS.getCalledValue() : nullptr);
00415   DEBUG(dbgs() << '\n');
00416 }
00417 
00418 void WinEHNumbering::calculateStateNumbers(const Function &F) {
00419   auto I = VisitedHandlers.insert(&F);
00420   if (!I.second)
00421     return; // We've already visited this handler, don't renumber it.
00422 
00423   DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
00424   SmallVector<ActionHandler *, 4> ActionList;
00425   for (const BasicBlock &BB : F) {
00426     for (const Instruction &I : BB) {
00427       const auto *CI = dyn_cast<CallInst>(&I);
00428       if (!CI || CI->doesNotThrow())
00429         continue;
00430       processCallSite(None, CI);
00431     }
00432     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
00433     if (!II)
00434       continue;
00435     const LandingPadInst *LPI = II->getLandingPadInst();
00436     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
00437     if (!ActionsCall)
00438       continue;
00439     assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
00440     parseEHActions(ActionsCall, ActionList);
00441     processCallSite(ActionList, II);
00442     ActionList.clear();
00443     FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
00444   }
00445 
00446   FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
00447 }
00448 
00449 /// clear - Clear out all the function-specific state. This returns this
00450 /// FunctionLoweringInfo to an empty state, ready to be used for a
00451 /// different function.
00452 void FunctionLoweringInfo::clear() {
00453   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
00454          "Not all catch info was assigned to a landing pad!");
00455 
00456   MBBMap.clear();
00457   ValueMap.clear();
00458   StaticAllocaMap.clear();
00459 #ifndef NDEBUG
00460   CatchInfoLost.clear();
00461   CatchInfoFound.clear();
00462 #endif
00463   LiveOutRegInfo.clear();
00464   VisitedBBs.clear();
00465   ArgDbgValues.clear();
00466   ByValArgFrameIndexMap.clear();
00467   RegFixups.clear();
00468   StatepointStackSlots.clear();
00469   PreferredExtendType.clear();
00470 }
00471 
00472 /// CreateReg - Allocate a single virtual register for the given type.
00473 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
00474   return RegInfo->createVirtualRegister(
00475       MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
00476 }
00477 
00478 /// CreateRegs - Allocate the appropriate number of virtual registers of
00479 /// the correctly promoted or expanded types.  Assign these registers
00480 /// consecutive vreg numbers and return the first assigned number.
00481 ///
00482 /// In the case that the given value has struct or array type, this function
00483 /// will assign registers for each member or element.
00484 ///
00485 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
00486   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
00487 
00488   SmallVector<EVT, 4> ValueVTs;
00489   ComputeValueVTs(*TLI, Ty, ValueVTs);
00490 
00491   unsigned FirstReg = 0;
00492   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
00493     EVT ValueVT = ValueVTs[Value];
00494     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
00495 
00496     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
00497     for (unsigned i = 0; i != NumRegs; ++i) {
00498       unsigned R = CreateReg(RegisterVT);
00499       if (!FirstReg) FirstReg = R;
00500     }
00501   }
00502   return FirstReg;
00503 }
00504 
00505 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
00506 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
00507 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
00508 /// the larger bit width by zero extension. The bit width must be no smaller
00509 /// than the LiveOutInfo's existing bit width.
00510 const FunctionLoweringInfo::LiveOutInfo *
00511 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
00512   if (!LiveOutRegInfo.inBounds(Reg))
00513     return nullptr;
00514 
00515   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
00516   if (!LOI->IsValid)
00517     return nullptr;
00518 
00519   if (BitWidth > LOI->KnownZero.getBitWidth()) {
00520     LOI->NumSignBits = 1;
00521     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
00522     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
00523   }
00524 
00525   return LOI;
00526 }
00527 
00528 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
00529 /// register based on the LiveOutInfo of its operands.
00530 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
00531   Type *Ty = PN->getType();
00532   if (!Ty->isIntegerTy() || Ty->isVectorTy())
00533     return;
00534 
00535   SmallVector<EVT, 1> ValueVTs;
00536   ComputeValueVTs(*TLI, Ty, ValueVTs);
00537   assert(ValueVTs.size() == 1 &&
00538          "PHIs with non-vector integer types should have a single VT.");
00539   EVT IntVT = ValueVTs[0];
00540 
00541   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
00542     return;
00543   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
00544   unsigned BitWidth = IntVT.getSizeInBits();
00545 
00546   unsigned DestReg = ValueMap[PN];
00547   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
00548     return;
00549   LiveOutRegInfo.grow(DestReg);
00550   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
00551 
00552   Value *V = PN->getIncomingValue(0);
00553   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
00554     DestLOI.NumSignBits = 1;
00555     APInt Zero(BitWidth, 0);
00556     DestLOI.KnownZero = Zero;
00557     DestLOI.KnownOne = Zero;
00558     return;
00559   }
00560 
00561   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00562     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
00563     DestLOI.NumSignBits = Val.getNumSignBits();
00564     DestLOI.KnownZero = ~Val;
00565     DestLOI.KnownOne = Val;
00566   } else {
00567     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
00568                                 "CopyToReg node was created.");
00569     unsigned SrcReg = ValueMap[V];
00570     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
00571       DestLOI.IsValid = false;
00572       return;
00573     }
00574     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
00575     if (!SrcLOI) {
00576       DestLOI.IsValid = false;
00577       return;
00578     }
00579     DestLOI = *SrcLOI;
00580   }
00581 
00582   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
00583          DestLOI.KnownOne.getBitWidth() == BitWidth &&
00584          "Masks should have the same bit width as the type.");
00585 
00586   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
00587     Value *V = PN->getIncomingValue(i);
00588     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
00589       DestLOI.NumSignBits = 1;
00590       APInt Zero(BitWidth, 0);
00591       DestLOI.KnownZero = Zero;
00592       DestLOI.KnownOne = Zero;
00593       return;
00594     }
00595 
00596     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00597       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
00598       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
00599       DestLOI.KnownZero &= ~Val;
00600       DestLOI.KnownOne &= Val;
00601       continue;
00602     }
00603 
00604     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
00605                                 "its CopyToReg node was created.");
00606     unsigned SrcReg = ValueMap[V];
00607     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
00608       DestLOI.IsValid = false;
00609       return;
00610     }
00611     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
00612     if (!SrcLOI) {
00613       DestLOI.IsValid = false;
00614       return;
00615     }
00616     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
00617     DestLOI.KnownZero &= SrcLOI->KnownZero;
00618     DestLOI.KnownOne &= SrcLOI->KnownOne;
00619   }
00620 }
00621 
00622 /// setArgumentFrameIndex - Record frame index for the byval
00623 /// argument. This overrides previous frame index entry for this argument,
00624 /// if any.
00625 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
00626                                                  int FI) {
00627   ByValArgFrameIndexMap[A] = FI;
00628 }
00629 
00630 /// getArgumentFrameIndex - Get frame index for the byval argument.
00631 /// If the argument does not have any assigned frame index then 0 is
00632 /// returned.
00633 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
00634   DenseMap<const Argument *, int>::iterator I =
00635     ByValArgFrameIndexMap.find(A);
00636   if (I != ByValArgFrameIndexMap.end())
00637     return I->second;
00638   DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
00639   return 0;
00640 }
00641 
00642 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
00643 /// being passed to this variadic function, and set the MachineModuleInfo's
00644 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
00645 /// reference to _fltused on Windows, which will link in MSVCRT's
00646 /// floating-point support.
00647 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
00648                                       MachineModuleInfo *MMI)
00649 {
00650   FunctionType *FT = cast<FunctionType>(
00651     I.getCalledValue()->getType()->getContainedType(0));
00652   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
00653     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
00654       Type* T = I.getArgOperand(i)->getType();
00655       for (auto i : post_order(T)) {
00656         if (i->isFloatingPointTy()) {
00657           MMI->setUsesVAFloatArgument(true);
00658           return;
00659         }
00660       }
00661     }
00662   }
00663 }
00664 
00665 /// AddLandingPadInfo - Extract the exception handling information from the
00666 /// landingpad instruction and add them to the specified machine module info.
00667 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
00668                              MachineBasicBlock *MBB) {
00669   MMI.addPersonality(MBB,
00670                      cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
00671 
00672   if (I.isCleanup())
00673     MMI.addCleanup(MBB);
00674 
00675   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
00676   //        but we need to do it this way because of how the DWARF EH emitter
00677   //        processes the clauses.
00678   for (unsigned i = I.getNumClauses(); i != 0; --i) {
00679     Value *Val = I.getClause(i - 1);
00680     if (I.isCatch(i - 1)) {
00681       MMI.addCatchTypeInfo(MBB,
00682                            dyn_cast<GlobalValue>(Val->stripPointerCasts()));
00683     } else {
00684       // Add filters in a list.
00685       Constant *CVal = cast<Constant>(Val);
00686       SmallVector<const GlobalValue*, 4> FilterList;
00687       for (User::op_iterator
00688              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
00689         FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
00690 
00691       MMI.addFilterTypeInfo(MBB, FilterList);
00692     }
00693   }
00694 }