FunctionLoweringInfo.cpp revision 210299
1130803Smarcel//===-- FunctionLoweringInfo.cpp ------------------------------------------===//
2130803Smarcel//
3130803Smarcel//                     The LLVM Compiler Infrastructure
4130803Smarcel//
5130803Smarcel// This file is distributed under the University of Illinois Open Source
6130803Smarcel// License. See LICENSE.TXT for details.
7130803Smarcel//
8130803Smarcel//===----------------------------------------------------------------------===//
9130803Smarcel//
10130803Smarcel// This implements routines for translating functions from LLVM IR into
11130803Smarcel// Machine IR.
12130803Smarcel//
13130803Smarcel//===----------------------------------------------------------------------===//
14130803Smarcel
15130803Smarcel#define DEBUG_TYPE "function-lowering-info"
16130803Smarcel#include "llvm/CodeGen/FunctionLoweringInfo.h"
17130803Smarcel#include "llvm/DerivedTypes.h"
18130803Smarcel#include "llvm/Function.h"
19130803Smarcel#include "llvm/Instructions.h"
20130803Smarcel#include "llvm/IntrinsicInst.h"
21130803Smarcel#include "llvm/LLVMContext.h"
22130803Smarcel#include "llvm/Module.h"
23130803Smarcel#include "llvm/CodeGen/Analysis.h"
24130803Smarcel#include "llvm/CodeGen/MachineFunction.h"
25130803Smarcel#include "llvm/CodeGen/MachineFrameInfo.h"
26130803Smarcel#include "llvm/CodeGen/MachineInstrBuilder.h"
27130803Smarcel#include "llvm/CodeGen/MachineModuleInfo.h"
28130803Smarcel#include "llvm/CodeGen/MachineRegisterInfo.h"
29130803Smarcel#include "llvm/Target/TargetRegisterInfo.h"
30130803Smarcel#include "llvm/Target/TargetData.h"
31130803Smarcel#include "llvm/Target/TargetFrameInfo.h"
32130803Smarcel#include "llvm/Target/TargetInstrInfo.h"
33130803Smarcel#include "llvm/Target/TargetLowering.h"
34130803Smarcel#include "llvm/Target/TargetOptions.h"
35130803Smarcel#include "llvm/Support/Debug.h"
36130803Smarcel#include "llvm/Support/ErrorHandling.h"
37130803Smarcel#include "llvm/Support/MathExtras.h"
38130803Smarcel#include <algorithm>
39130803Smarcelusing namespace llvm;
40130803Smarcel
41130803Smarcel/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
42130803Smarcel/// PHI nodes or outside of the basic block that defines it, or used by a
43130803Smarcel/// switch or atomic instruction, which may expand to multiple basic blocks.
44130803Smarcelstatic bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
45130803Smarcel  if (I->use_empty()) return false;
46130803Smarcel  if (isa<PHINode>(I)) return true;
47130803Smarcel  const BasicBlock *BB = I->getParent();
48130803Smarcel  for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end();
49130803Smarcel        UI != E; ++UI) {
50130803Smarcel    const User *U = *UI;
51130803Smarcel    if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
52130803Smarcel      return true;
53130803Smarcel  }
54130803Smarcel  return false;
55130803Smarcel}
56130803Smarcel
57130803Smarcel/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
58130803Smarcel/// entry block, return true.  This includes arguments used by switches, since
59130803Smarcel/// the switch may expand into multiple basic blocks.
60130803Smarcelstatic bool isOnlyUsedInEntryBlock(const Argument *A, bool EnableFastISel) {
61130803Smarcel  // With FastISel active, we may be splitting blocks, so force creation
62130803Smarcel  // of virtual registers for all non-dead arguments.
63130803Smarcel  if (EnableFastISel)
64130803Smarcel    return A->use_empty();
65130803Smarcel
66130803Smarcel  const BasicBlock *Entry = A->getParent()->begin();
67130803Smarcel  for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
68130803Smarcel       UI != E; ++UI) {
69130803Smarcel    const User *U = *UI;
70130803Smarcel    if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
71130803Smarcel      return false;  // Use not in entry block.
72130803Smarcel  }
73130803Smarcel  return true;
74130803Smarcel}
75130803Smarcel
76130803SmarcelFunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli)
77130803Smarcel  : TLI(tli) {
78130803Smarcel}
79130803Smarcel
80130803Smarcelvoid FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
81130803Smarcel  Fn = &fn;
82130803Smarcel  MF = &mf;
83130803Smarcel  RegInfo = &MF->getRegInfo();
84130803Smarcel
85130803Smarcel  // Check whether the function can return without sret-demotion.
86130803Smarcel  SmallVector<ISD::OutputArg, 4> Outs;
87130803Smarcel  GetReturnInfo(Fn->getReturnType(),
88130803Smarcel                Fn->getAttributes().getRetAttributes(), Outs, TLI);
89130803Smarcel  CanLowerReturn = TLI.CanLowerReturn(Fn->getCallingConv(), Fn->isVarArg(),
90130803Smarcel                                      Outs, Fn->getContext());
91130803Smarcel
92130803Smarcel  // Create a vreg for each argument register that is not dead and is used
93130803Smarcel  // outside of the entry block for the function.
94130803Smarcel  for (Function::const_arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
95130803Smarcel       AI != E; ++AI)
96130803Smarcel    if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
97130803Smarcel      InitializeRegForValue(AI);
98130803Smarcel
99  // Initialize the mapping of values to registers.  This is only set up for
100  // instruction values that are used outside of the block that defines
101  // them.
102  Function::const_iterator BB = Fn->begin(), EB = Fn->end();
103  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
104    if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
105      if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
106        const Type *Ty = AI->getAllocatedType();
107        uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
108        unsigned Align =
109          std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
110                   AI->getAlignment());
111
112        TySize *= CUI->getZExtValue();   // Get total allocated size.
113        if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
114        StaticAllocaMap[AI] =
115          MF->getFrameInfo()->CreateStackObject(TySize, Align, false);
116      }
117
118  for (; BB != EB; ++BB)
119    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
120      if (isUsedOutsideOfDefiningBlock(I))
121        if (!isa<AllocaInst>(I) ||
122            !StaticAllocaMap.count(cast<AllocaInst>(I)))
123          InitializeRegForValue(I);
124
125  // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
126  // also creates the initial PHI MachineInstrs, though none of the input
127  // operands are populated.
128  for (BB = Fn->begin(); BB != EB; ++BB) {
129    MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
130    MBBMap[BB] = MBB;
131    MF->push_back(MBB);
132
133    // Transfer the address-taken flag. This is necessary because there could
134    // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
135    // the first one should be marked.
136    if (BB->hasAddressTaken())
137      MBB->setHasAddressTaken();
138
139    // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
140    // appropriate.
141    for (BasicBlock::const_iterator I = BB->begin();
142         const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
143      if (PN->use_empty()) continue;
144
145      DebugLoc DL = PN->getDebugLoc();
146      unsigned PHIReg = ValueMap[PN];
147      assert(PHIReg && "PHI node does not have an assigned virtual register!");
148
149      SmallVector<EVT, 4> ValueVTs;
150      ComputeValueVTs(TLI, PN->getType(), ValueVTs);
151      for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
152        EVT VT = ValueVTs[vti];
153        unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
154        const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
155        for (unsigned i = 0; i != NumRegisters; ++i)
156          BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
157        PHIReg += NumRegisters;
158      }
159    }
160  }
161
162  // Mark landing pad blocks.
163  for (BB = Fn->begin(); BB != EB; ++BB)
164    if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
165      MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
166}
167
168/// clear - Clear out all the function-specific state. This returns this
169/// FunctionLoweringInfo to an empty state, ready to be used for a
170/// different function.
171void FunctionLoweringInfo::clear() {
172  assert(CatchInfoFound.size() == CatchInfoLost.size() &&
173         "Not all catch info was assigned to a landing pad!");
174
175  MBBMap.clear();
176  ValueMap.clear();
177  StaticAllocaMap.clear();
178#ifndef NDEBUG
179  CatchInfoLost.clear();
180  CatchInfoFound.clear();
181#endif
182  LiveOutRegInfo.clear();
183  ArgDbgValues.clear();
184  RegFixups.clear();
185}
186
187/// CreateReg - Allocate a single virtual register for the given type.
188unsigned FunctionLoweringInfo::CreateReg(EVT VT) {
189  return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
190}
191
192/// CreateRegs - Allocate the appropriate number of virtual registers of
193/// the correctly promoted or expanded types.  Assign these registers
194/// consecutive vreg numbers and return the first assigned number.
195///
196/// In the case that the given value has struct or array type, this function
197/// will assign registers for each member or element.
198///
199unsigned FunctionLoweringInfo::CreateRegs(const Type *Ty) {
200  SmallVector<EVT, 4> ValueVTs;
201  ComputeValueVTs(TLI, Ty, ValueVTs);
202
203  unsigned FirstReg = 0;
204  for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
205    EVT ValueVT = ValueVTs[Value];
206    EVT RegisterVT = TLI.getRegisterType(Ty->getContext(), ValueVT);
207
208    unsigned NumRegs = TLI.getNumRegisters(Ty->getContext(), ValueVT);
209    for (unsigned i = 0; i != NumRegs; ++i) {
210      unsigned R = CreateReg(RegisterVT);
211      if (!FirstReg) FirstReg = R;
212    }
213  }
214  return FirstReg;
215}
216
217/// AddCatchInfo - Extract the personality and type infos from an eh.selector
218/// call, and add them to the specified machine basic block.
219void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
220                        MachineBasicBlock *MBB) {
221  // Inform the MachineModuleInfo of the personality for this landing pad.
222  const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
223  assert(CE->getOpcode() == Instruction::BitCast &&
224         isa<Function>(CE->getOperand(0)) &&
225         "Personality should be a function");
226  MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
227
228  // Gather all the type infos for this landing pad and pass them along to
229  // MachineModuleInfo.
230  std::vector<const GlobalVariable *> TyInfo;
231  unsigned N = I.getNumArgOperands();
232
233  for (unsigned i = N - 1; i > 1; --i) {
234    if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
235      unsigned FilterLength = CI->getZExtValue();
236      unsigned FirstCatch = i + FilterLength + !FilterLength;
237      assert(FirstCatch <= N && "Invalid filter length");
238
239      if (FirstCatch < N) {
240        TyInfo.reserve(N - FirstCatch);
241        for (unsigned j = FirstCatch; j < N; ++j)
242          TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
243        MMI->addCatchTypeInfo(MBB, TyInfo);
244        TyInfo.clear();
245      }
246
247      if (!FilterLength) {
248        // Cleanup.
249        MMI->addCleanup(MBB);
250      } else {
251        // Filter.
252        TyInfo.reserve(FilterLength - 1);
253        for (unsigned j = i + 1; j < FirstCatch; ++j)
254          TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
255        MMI->addFilterTypeInfo(MBB, TyInfo);
256        TyInfo.clear();
257      }
258
259      N = i;
260    }
261  }
262
263  if (N > 2) {
264    TyInfo.reserve(N - 2);
265    for (unsigned j = 2; j < N; ++j)
266      TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
267    MMI->addCatchTypeInfo(MBB, TyInfo);
268  }
269}
270
271void llvm::CopyCatchInfo(const BasicBlock *SrcBB, const BasicBlock *DestBB,
272                         MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
273  for (BasicBlock::const_iterator I = SrcBB->begin(), E = --SrcBB->end();
274       I != E; ++I)
275    if (const EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
276      // Apply the catch info to DestBB.
277      AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
278#ifndef NDEBUG
279      if (!FLI.MBBMap[SrcBB]->isLandingPad())
280        FLI.CatchInfoFound.insert(EHSel);
281#endif
282    }
283}
284