LLVM API Documentation

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/IR/DataLayout.h"
00024 #include "llvm/IR/DebugInfo.h"
00025 #include "llvm/IR/DerivedTypes.h"
00026 #include "llvm/IR/Function.h"
00027 #include "llvm/IR/Instructions.h"
00028 #include "llvm/IR/IntrinsicInst.h"
00029 #include "llvm/IR/LLVMContext.h"
00030 #include "llvm/IR/Module.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/MathExtras.h"
00034 #include "llvm/Target/TargetFrameLowering.h"
00035 #include "llvm/Target/TargetInstrInfo.h"
00036 #include "llvm/Target/TargetLowering.h"
00037 #include "llvm/Target/TargetOptions.h"
00038 #include "llvm/Target/TargetRegisterInfo.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 #include <algorithm>
00041 using namespace llvm;
00042 
00043 #define DEBUG_TYPE "function-lowering-info"
00044 
00045 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
00046 /// PHI nodes or outside of the basic block that defines it, or used by a
00047 /// switch or atomic instruction, which may expand to multiple basic blocks.
00048 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
00049   if (I->use_empty()) return false;
00050   if (isa<PHINode>(I)) return true;
00051   const BasicBlock *BB = I->getParent();
00052   for (const User *U : I->users())
00053     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
00054       return true;
00055 
00056   return false;
00057 }
00058 
00059 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
00060   // For the users of the source value being used for compare instruction, if
00061   // the number of signed predicate is greater than unsigned predicate, we
00062   // prefer to use SIGN_EXTEND.
00063   //
00064   // With this optimization, we would be able to reduce some redundant sign or
00065   // zero extension instruction, and eventually more machine CSE opportunities
00066   // can be exposed.
00067   ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
00068   unsigned NumOfSigned = 0, NumOfUnsigned = 0;
00069   for (const User *U : V->users()) {
00070     if (const auto *CI = dyn_cast<CmpInst>(U)) {
00071       NumOfSigned += CI->isSigned();
00072       NumOfUnsigned += CI->isUnsigned();
00073     }
00074   }
00075   if (NumOfSigned > NumOfUnsigned)
00076     ExtendKind = ISD::SIGN_EXTEND;
00077 
00078   return ExtendKind;
00079 }
00080 
00081 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
00082                                SelectionDAG *DAG) {
00083   Fn = &fn;
00084   MF = &mf;
00085   TLI = MF->getSubtarget().getTargetLowering();
00086   RegInfo = &MF->getRegInfo();
00087 
00088   // Check whether the function can return without sret-demotion.
00089   SmallVector<ISD::OutputArg, 4> Outs;
00090   GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
00091   CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
00092                                        Fn->isVarArg(), Outs, Fn->getContext());
00093 
00094   // Initialize the mapping of values to registers.  This is only set up for
00095   // instruction values that are used outside of the block that defines
00096   // them.
00097   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
00098   for (; BB != EB; ++BB)
00099     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
00100          I != E; ++I) {
00101       if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
00102         // Static allocas can be folded into the initial stack frame adjustment.
00103         if (AI->isStaticAlloca()) {
00104           const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
00105           Type *Ty = AI->getAllocatedType();
00106           uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
00107           unsigned Align =
00108               std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
00109                        AI->getAlignment());
00110 
00111           TySize *= CUI->getZExtValue();   // Get total allocated size.
00112           if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
00113 
00114           StaticAllocaMap[AI] =
00115             MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
00116 
00117         } else {
00118           unsigned Align = std::max(
00119               (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
00120                 AI->getAllocatedType()),
00121               AI->getAlignment());
00122           unsigned StackAlign =
00123               MF->getSubtarget().getFrameLowering()->getStackAlignment();
00124           if (Align <= StackAlign)
00125             Align = 0;
00126           // Inform the Frame Information that we have variable-sized objects.
00127           MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
00128         }
00129       }
00130 
00131       // Look for inline asm that clobbers the SP register.
00132       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
00133         ImmutableCallSite CS(I);
00134         if (isa<InlineAsm>(CS.getCalledValue())) {
00135           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
00136           const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00137           std::vector<TargetLowering::AsmOperandInfo> Ops =
00138               TLI->ParseConstraints(TRI, CS);
00139           for (size_t I = 0, E = Ops.size(); I != E; ++I) {
00140             TargetLowering::AsmOperandInfo &Op = Ops[I];
00141             if (Op.Type == InlineAsm::isClobber) {
00142               // Clobbers don't have SDValue operands, hence SDValue().
00143               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
00144               std::pair<unsigned, const TargetRegisterClass *> PhysReg =
00145                   TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
00146                                                     Op.ConstraintVT);
00147               if (PhysReg.first == SP)
00148                 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
00149             }
00150           }
00151         }
00152       }
00153 
00154       // Look for calls to the @llvm.va_start intrinsic. We can omit some
00155       // prologue boilerplate for variadic functions that don't examine their
00156       // arguments.
00157       if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
00158         if (II->getIntrinsicID() == Intrinsic::vastart)
00159           MF->getFrameInfo()->setHasVAStart(true);
00160       }
00161 
00162       // If we have a musttail call in a variadic funciton, we need to ensure we
00163       // forward implicit register parameters.
00164       if (const auto *CI = dyn_cast<CallInst>(I)) {
00165         if (CI->isMustTailCall() && Fn->isVarArg())
00166           MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
00167       }
00168 
00169       // Mark values used outside their block as exported, by allocating
00170       // a virtual register for them.
00171       if (isUsedOutsideOfDefiningBlock(I))
00172         if (!isa<AllocaInst>(I) ||
00173             !StaticAllocaMap.count(cast<AllocaInst>(I)))
00174           InitializeRegForValue(I);
00175 
00176       // Collect llvm.dbg.declare information. This is done now instead of
00177       // during the initial isel pass through the IR so that it is done
00178       // in a predictable order.
00179       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
00180         MachineModuleInfo &MMI = MF->getMMI();
00181         DIVariable DIVar(DI->getVariable());
00182         assert((!DIVar || DIVar.isVariable()) &&
00183           "Variable in DbgDeclareInst should be either null or a DIVariable.");
00184         if (MMI.hasDebugInfo() &&
00185             DIVar &&
00186             !DI->getDebugLoc().isUnknown()) {
00187           // Don't handle byval struct arguments or VLAs, for example.
00188           // Non-byval arguments are handled here (they refer to the stack
00189           // temporary alloca at this point).
00190           const Value *Address = DI->getAddress();
00191           if (Address) {
00192             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
00193               Address = BCI->getOperand(0);
00194             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
00195               DenseMap<const AllocaInst *, int>::iterator SI =
00196                 StaticAllocaMap.find(AI);
00197               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
00198                 int FI = SI->second;
00199                 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
00200                                        FI, DI->getDebugLoc());
00201               }
00202             }
00203           }
00204         }
00205       }
00206 
00207       // Decide the preferred extend type for a value.
00208       PreferredExtendType[I] = getPreferredExtendForValue(I);
00209     }
00210 
00211   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
00212   // also creates the initial PHI MachineInstrs, though none of the input
00213   // operands are populated.
00214   for (BB = Fn->begin(); BB != EB; ++BB) {
00215     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
00216     MBBMap[BB] = MBB;
00217     MF->push_back(MBB);
00218 
00219     // Transfer the address-taken flag. This is necessary because there could
00220     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
00221     // the first one should be marked.
00222     if (BB->hasAddressTaken())
00223       MBB->setHasAddressTaken();
00224 
00225     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
00226     // appropriate.
00227     for (BasicBlock::const_iterator I = BB->begin();
00228          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
00229       if (PN->use_empty()) continue;
00230 
00231       // Skip empty types
00232       if (PN->getType()->isEmptyTy())
00233         continue;
00234 
00235       DebugLoc DL = PN->getDebugLoc();
00236       unsigned PHIReg = ValueMap[PN];
00237       assert(PHIReg && "PHI node does not have an assigned virtual register!");
00238 
00239       SmallVector<EVT, 4> ValueVTs;
00240       ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
00241       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
00242         EVT VT = ValueVTs[vti];
00243         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
00244         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00245         for (unsigned i = 0; i != NumRegisters; ++i)
00246           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
00247         PHIReg += NumRegisters;
00248       }
00249     }
00250   }
00251 
00252   // Mark landing pad blocks.
00253   for (BB = Fn->begin(); BB != EB; ++BB)
00254     if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
00255       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
00256 }
00257 
00258 /// clear - Clear out all the function-specific state. This returns this
00259 /// FunctionLoweringInfo to an empty state, ready to be used for a
00260 /// different function.
00261 void FunctionLoweringInfo::clear() {
00262   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
00263          "Not all catch info was assigned to a landing pad!");
00264 
00265   MBBMap.clear();
00266   ValueMap.clear();
00267   StaticAllocaMap.clear();
00268 #ifndef NDEBUG
00269   CatchInfoLost.clear();
00270   CatchInfoFound.clear();
00271 #endif
00272   LiveOutRegInfo.clear();
00273   VisitedBBs.clear();
00274   ArgDbgValues.clear();
00275   ByValArgFrameIndexMap.clear();
00276   RegFixups.clear();
00277   StatepointStackSlots.clear();
00278   PreferredExtendType.clear();
00279 }
00280 
00281 /// CreateReg - Allocate a single virtual register for the given type.
00282 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
00283   return RegInfo->createVirtualRegister(
00284       MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
00285 }
00286 
00287 /// CreateRegs - Allocate the appropriate number of virtual registers of
00288 /// the correctly promoted or expanded types.  Assign these registers
00289 /// consecutive vreg numbers and return the first assigned number.
00290 ///
00291 /// In the case that the given value has struct or array type, this function
00292 /// will assign registers for each member or element.
00293 ///
00294 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
00295   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
00296 
00297   SmallVector<EVT, 4> ValueVTs;
00298   ComputeValueVTs(*TLI, Ty, ValueVTs);
00299 
00300   unsigned FirstReg = 0;
00301   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
00302     EVT ValueVT = ValueVTs[Value];
00303     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
00304 
00305     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
00306     for (unsigned i = 0; i != NumRegs; ++i) {
00307       unsigned R = CreateReg(RegisterVT);
00308       if (!FirstReg) FirstReg = R;
00309     }
00310   }
00311   return FirstReg;
00312 }
00313 
00314 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
00315 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
00316 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
00317 /// the larger bit width by zero extension. The bit width must be no smaller
00318 /// than the LiveOutInfo's existing bit width.
00319 const FunctionLoweringInfo::LiveOutInfo *
00320 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
00321   if (!LiveOutRegInfo.inBounds(Reg))
00322     return nullptr;
00323 
00324   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
00325   if (!LOI->IsValid)
00326     return nullptr;
00327 
00328   if (BitWidth > LOI->KnownZero.getBitWidth()) {
00329     LOI->NumSignBits = 1;
00330     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
00331     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
00332   }
00333 
00334   return LOI;
00335 }
00336 
00337 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
00338 /// register based on the LiveOutInfo of its operands.
00339 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
00340   Type *Ty = PN->getType();
00341   if (!Ty->isIntegerTy() || Ty->isVectorTy())
00342     return;
00343 
00344   SmallVector<EVT, 1> ValueVTs;
00345   ComputeValueVTs(*TLI, Ty, ValueVTs);
00346   assert(ValueVTs.size() == 1 &&
00347          "PHIs with non-vector integer types should have a single VT.");
00348   EVT IntVT = ValueVTs[0];
00349 
00350   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
00351     return;
00352   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
00353   unsigned BitWidth = IntVT.getSizeInBits();
00354 
00355   unsigned DestReg = ValueMap[PN];
00356   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
00357     return;
00358   LiveOutRegInfo.grow(DestReg);
00359   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
00360 
00361   Value *V = PN->getIncomingValue(0);
00362   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
00363     DestLOI.NumSignBits = 1;
00364     APInt Zero(BitWidth, 0);
00365     DestLOI.KnownZero = Zero;
00366     DestLOI.KnownOne = Zero;
00367     return;
00368   }
00369 
00370   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00371     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
00372     DestLOI.NumSignBits = Val.getNumSignBits();
00373     DestLOI.KnownZero = ~Val;
00374     DestLOI.KnownOne = Val;
00375   } else {
00376     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
00377                                 "CopyToReg node was created.");
00378     unsigned SrcReg = ValueMap[V];
00379     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
00380       DestLOI.IsValid = false;
00381       return;
00382     }
00383     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
00384     if (!SrcLOI) {
00385       DestLOI.IsValid = false;
00386       return;
00387     }
00388     DestLOI = *SrcLOI;
00389   }
00390 
00391   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
00392          DestLOI.KnownOne.getBitWidth() == BitWidth &&
00393          "Masks should have the same bit width as the type.");
00394 
00395   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
00396     Value *V = PN->getIncomingValue(i);
00397     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
00398       DestLOI.NumSignBits = 1;
00399       APInt Zero(BitWidth, 0);
00400       DestLOI.KnownZero = Zero;
00401       DestLOI.KnownOne = Zero;
00402       return;
00403     }
00404 
00405     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00406       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
00407       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
00408       DestLOI.KnownZero &= ~Val;
00409       DestLOI.KnownOne &= Val;
00410       continue;
00411     }
00412 
00413     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
00414                                 "its CopyToReg node was created.");
00415     unsigned SrcReg = ValueMap[V];
00416     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
00417       DestLOI.IsValid = false;
00418       return;
00419     }
00420     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
00421     if (!SrcLOI) {
00422       DestLOI.IsValid = false;
00423       return;
00424     }
00425     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
00426     DestLOI.KnownZero &= SrcLOI->KnownZero;
00427     DestLOI.KnownOne &= SrcLOI->KnownOne;
00428   }
00429 }
00430 
00431 /// setArgumentFrameIndex - Record frame index for the byval
00432 /// argument. This overrides previous frame index entry for this argument,
00433 /// if any.
00434 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
00435                                                  int FI) {
00436   ByValArgFrameIndexMap[A] = FI;
00437 }
00438 
00439 /// getArgumentFrameIndex - Get frame index for the byval argument.
00440 /// If the argument does not have any assigned frame index then 0 is
00441 /// returned.
00442 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
00443   DenseMap<const Argument *, int>::iterator I =
00444     ByValArgFrameIndexMap.find(A);
00445   if (I != ByValArgFrameIndexMap.end())
00446     return I->second;
00447   DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
00448   return 0;
00449 }
00450 
00451 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
00452 /// being passed to this variadic function, and set the MachineModuleInfo's
00453 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
00454 /// reference to _fltused on Windows, which will link in MSVCRT's
00455 /// floating-point support.
00456 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
00457                                       MachineModuleInfo *MMI)
00458 {
00459   FunctionType *FT = cast<FunctionType>(
00460     I.getCalledValue()->getType()->getContainedType(0));
00461   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
00462     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
00463       Type* T = I.getArgOperand(i)->getType();
00464       for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
00465            i != e; ++i) {
00466         if (i->isFloatingPointTy()) {
00467           MMI->setUsesVAFloatArgument(true);
00468           return;
00469         }
00470       }
00471     }
00472   }
00473 }
00474 
00475 /// AddLandingPadInfo - Extract the exception handling information from the
00476 /// landingpad instruction and add them to the specified machine module info.
00477 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
00478                              MachineBasicBlock *MBB) {
00479   MMI.addPersonality(MBB,
00480                      cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
00481 
00482   if (I.isCleanup())
00483     MMI.addCleanup(MBB);
00484 
00485   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
00486   //        but we need to do it this way because of how the DWARF EH emitter
00487   //        processes the clauses.
00488   for (unsigned i = I.getNumClauses(); i != 0; --i) {
00489     Value *Val = I.getClause(i - 1);
00490     if (I.isCatch(i - 1)) {
00491       MMI.addCatchTypeInfo(MBB,
00492                            dyn_cast<GlobalValue>(Val->stripPointerCasts()));
00493     } else {
00494       // Add filters in a list.
00495       Constant *CVal = cast<Constant>(Val);
00496       SmallVector<const GlobalValue*, 4> FilterList;
00497       for (User::op_iterator
00498              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
00499         FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
00500 
00501       MMI.addFilterTypeInfo(MBB, FilterList);
00502     }
00503   }
00504 }