3c24f95039bbcb4d40a41210d1d28a7466e7e27e
[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 #define DEBUG_TYPE "function-lowering-info"
16 #include "llvm/CodeGen/FunctionLoweringInfo.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/DebugInfo.h"
25 #include "llvm/IR/DataLayout.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/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
44 /// PHI nodes or outside of the basic block that defines it, or used by a
45 /// switch or atomic instruction, which may expand to multiple basic blocks.
46 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
47   if (I->use_empty()) return false;
48   if (isa<PHINode>(I)) return true;
49   const BasicBlock *BB = I->getParent();
50   for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end();
51         UI != E; ++UI) {
52     const User *U = *UI;
53     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
54       return true;
55   }
56   return false;
57 }
58
59 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
60                                SelectionDAG *DAG) {
61   const TargetLowering *TLI = TM.getTargetLowering();
62
63   Fn = &fn;
64   MF = &mf;
65   RegInfo = &MF->getRegInfo();
66
67   // Check whether the function can return without sret-demotion.
68   SmallVector<ISD::OutputArg, 4> Outs;
69   GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
70   CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
71                                        Fn->isVarArg(),
72                                        Outs, Fn->getContext());
73
74   // Initialize the mapping of values to registers.  This is only set up for
75   // instruction values that are used outside of the block that defines
76   // them.
77   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
78   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
79     if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
80       // Don't fold inalloca allocas or other dynamic allocas into the initial
81       // stack frame allocation, even if they are in the entry block.
82       if (!AI->isStaticAlloca())
83         continue;
84
85       if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
86         Type *Ty = AI->getAllocatedType();
87         uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
88         unsigned Align =
89           std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
90                    AI->getAlignment());
91
92         TySize *= CUI->getZExtValue();   // Get total allocated size.
93         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
94
95         StaticAllocaMap[AI] =
96           MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
97       }
98     }
99
100   for (; BB != EB; ++BB)
101     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
102          I != E; ++I) {
103       // Look for dynamic allocas.
104       if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
105         if (!AI->isStaticAlloca()) {
106           unsigned Align = std::max(
107               (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
108                 AI->getAllocatedType()),
109               AI->getAlignment());
110           unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
111           if (Align <= StackAlign)
112             Align = 0;
113           // Inform the Frame Information that we have variable-sized objects.
114           MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
115         }
116       }
117
118       // Look for inline asm that clobbers the SP register.
119       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
120         ImmutableCallSite CS(I);
121         if (const InlineAsm *IA = dyn_cast<InlineAsm>(CS.getCalledValue())) {
122           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
123           std::vector<TargetLowering::AsmOperandInfo> Ops =
124             TLI->ParseConstraints(CS);
125           for (size_t I = 0, E = Ops.size(); I != E; ++I) {
126             TargetLowering::AsmOperandInfo &Op = Ops[I];
127             if (Op.Type == InlineAsm::isClobber) {
128               // Clobbers don't have SDValue operands, hence SDValue().
129               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
130               std::pair<unsigned, const TargetRegisterClass*> PhysReg =
131                 TLI->getRegForInlineAsmConstraint(Op.ConstraintCode,
132                                                   Op.ConstraintVT);
133               if (PhysReg.first == SP)
134                 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
135             }
136           }
137         }
138       }
139
140       // Mark values used outside their block as exported, by allocating
141       // a virtual register for them.
142       if (isUsedOutsideOfDefiningBlock(I))
143         if (!isa<AllocaInst>(I) ||
144             !StaticAllocaMap.count(cast<AllocaInst>(I)))
145           InitializeRegForValue(I);
146
147       // Collect llvm.dbg.declare information. This is done now instead of
148       // during the initial isel pass through the IR so that it is done
149       // in a predictable order.
150       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
151         MachineModuleInfo &MMI = MF->getMMI();
152         DIVariable DIVar(DI->getVariable());
153         assert((!DIVar || DIVar.isVariable()) &&
154           "Variable in DbgDeclareInst should be either null or a DIVariable.");
155         if (MMI.hasDebugInfo() &&
156             DIVar &&
157             !DI->getDebugLoc().isUnknown()) {
158           // Don't handle byval struct arguments or VLAs, for example.
159           // Non-byval arguments are handled here (they refer to the stack
160           // temporary alloca at this point).
161           const Value *Address = DI->getAddress();
162           if (Address) {
163             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
164               Address = BCI->getOperand(0);
165             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
166               DenseMap<const AllocaInst *, int>::iterator SI =
167                 StaticAllocaMap.find(AI);
168               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
169                 int FI = SI->second;
170                 MMI.setVariableDbgInfo(DI->getVariable(),
171                                        FI, DI->getDebugLoc());
172               }
173             }
174           }
175         }
176       }
177     }
178
179   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
180   // also creates the initial PHI MachineInstrs, though none of the input
181   // operands are populated.
182   for (BB = Fn->begin(); BB != EB; ++BB) {
183     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
184     MBBMap[BB] = MBB;
185     MF->push_back(MBB);
186
187     // Transfer the address-taken flag. This is necessary because there could
188     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
189     // the first one should be marked.
190     if (BB->hasAddressTaken())
191       MBB->setHasAddressTaken();
192
193     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
194     // appropriate.
195     for (BasicBlock::const_iterator I = BB->begin();
196          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
197       if (PN->use_empty()) continue;
198
199       // Skip empty types
200       if (PN->getType()->isEmptyTy())
201         continue;
202
203       DebugLoc DL = PN->getDebugLoc();
204       unsigned PHIReg = ValueMap[PN];
205       assert(PHIReg && "PHI node does not have an assigned virtual register!");
206
207       SmallVector<EVT, 4> ValueVTs;
208       ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
209       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
210         EVT VT = ValueVTs[vti];
211         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
212         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
213         for (unsigned i = 0; i != NumRegisters; ++i)
214           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
215         PHIReg += NumRegisters;
216       }
217     }
218   }
219
220   // Mark landing pad blocks.
221   for (BB = Fn->begin(); BB != EB; ++BB)
222     if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
223       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
224 }
225
226 /// clear - Clear out all the function-specific state. This returns this
227 /// FunctionLoweringInfo to an empty state, ready to be used for a
228 /// different function.
229 void FunctionLoweringInfo::clear() {
230   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
231          "Not all catch info was assigned to a landing pad!");
232
233   MBBMap.clear();
234   ValueMap.clear();
235   StaticAllocaMap.clear();
236 #ifndef NDEBUG
237   CatchInfoLost.clear();
238   CatchInfoFound.clear();
239 #endif
240   LiveOutRegInfo.clear();
241   VisitedBBs.clear();
242   ArgDbgValues.clear();
243   ByValArgFrameIndexMap.clear();
244   RegFixups.clear();
245 }
246
247 /// CreateReg - Allocate a single virtual register for the given type.
248 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
249   return RegInfo->
250     createVirtualRegister(TM.getTargetLowering()->getRegClassFor(VT));
251 }
252
253 /// CreateRegs - Allocate the appropriate number of virtual registers of
254 /// the correctly promoted or expanded types.  Assign these registers
255 /// consecutive vreg numbers and return the first assigned number.
256 ///
257 /// In the case that the given value has struct or array type, this function
258 /// will assign registers for each member or element.
259 ///
260 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
261   const TargetLowering *TLI = TM.getTargetLowering();
262
263   SmallVector<EVT, 4> ValueVTs;
264   ComputeValueVTs(*TLI, Ty, ValueVTs);
265
266   unsigned FirstReg = 0;
267   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
268     EVT ValueVT = ValueVTs[Value];
269     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
270
271     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
272     for (unsigned i = 0; i != NumRegs; ++i) {
273       unsigned R = CreateReg(RegisterVT);
274       if (!FirstReg) FirstReg = R;
275     }
276   }
277   return FirstReg;
278 }
279
280 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
281 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
282 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
283 /// the larger bit width by zero extension. The bit width must be no smaller
284 /// than the LiveOutInfo's existing bit width.
285 const FunctionLoweringInfo::LiveOutInfo *
286 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
287   if (!LiveOutRegInfo.inBounds(Reg))
288     return NULL;
289
290   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
291   if (!LOI->IsValid)
292     return NULL;
293
294   if (BitWidth > LOI->KnownZero.getBitWidth()) {
295     LOI->NumSignBits = 1;
296     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
297     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
298   }
299
300   return LOI;
301 }
302
303 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
304 /// register based on the LiveOutInfo of its operands.
305 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
306   Type *Ty = PN->getType();
307   if (!Ty->isIntegerTy() || Ty->isVectorTy())
308     return;
309
310   const TargetLowering *TLI = TM.getTargetLowering();
311
312   SmallVector<EVT, 1> ValueVTs;
313   ComputeValueVTs(*TLI, Ty, ValueVTs);
314   assert(ValueVTs.size() == 1 &&
315          "PHIs with non-vector integer types should have a single VT.");
316   EVT IntVT = ValueVTs[0];
317
318   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
319     return;
320   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
321   unsigned BitWidth = IntVT.getSizeInBits();
322
323   unsigned DestReg = ValueMap[PN];
324   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
325     return;
326   LiveOutRegInfo.grow(DestReg);
327   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
328
329   Value *V = PN->getIncomingValue(0);
330   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
331     DestLOI.NumSignBits = 1;
332     APInt Zero(BitWidth, 0);
333     DestLOI.KnownZero = Zero;
334     DestLOI.KnownOne = Zero;
335     return;
336   }
337
338   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
339     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
340     DestLOI.NumSignBits = Val.getNumSignBits();
341     DestLOI.KnownZero = ~Val;
342     DestLOI.KnownOne = Val;
343   } else {
344     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
345                                 "CopyToReg node was created.");
346     unsigned SrcReg = ValueMap[V];
347     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
348       DestLOI.IsValid = false;
349       return;
350     }
351     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
352     if (!SrcLOI) {
353       DestLOI.IsValid = false;
354       return;
355     }
356     DestLOI = *SrcLOI;
357   }
358
359   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
360          DestLOI.KnownOne.getBitWidth() == BitWidth &&
361          "Masks should have the same bit width as the type.");
362
363   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
364     Value *V = PN->getIncomingValue(i);
365     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
366       DestLOI.NumSignBits = 1;
367       APInt Zero(BitWidth, 0);
368       DestLOI.KnownZero = Zero;
369       DestLOI.KnownOne = Zero;
370       return;
371     }
372
373     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
374       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
375       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
376       DestLOI.KnownZero &= ~Val;
377       DestLOI.KnownOne &= Val;
378       continue;
379     }
380
381     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
382                                 "its CopyToReg node was created.");
383     unsigned SrcReg = ValueMap[V];
384     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
385       DestLOI.IsValid = false;
386       return;
387     }
388     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
389     if (!SrcLOI) {
390       DestLOI.IsValid = false;
391       return;
392     }
393     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
394     DestLOI.KnownZero &= SrcLOI->KnownZero;
395     DestLOI.KnownOne &= SrcLOI->KnownOne;
396   }
397 }
398
399 /// setArgumentFrameIndex - Record frame index for the byval
400 /// argument. This overrides previous frame index entry for this argument,
401 /// if any.
402 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
403                                                  int FI) {
404   ByValArgFrameIndexMap[A] = FI;
405 }
406
407 /// getArgumentFrameIndex - Get frame index for the byval argument.
408 /// If the argument does not have any assigned frame index then 0 is
409 /// returned.
410 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
411   DenseMap<const Argument *, int>::iterator I =
412     ByValArgFrameIndexMap.find(A);
413   if (I != ByValArgFrameIndexMap.end())
414     return I->second;
415   DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
416   return 0;
417 }
418
419 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
420 /// being passed to this variadic function, and set the MachineModuleInfo's
421 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
422 /// reference to _fltused on Windows, which will link in MSVCRT's
423 /// floating-point support.
424 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
425                                       MachineModuleInfo *MMI)
426 {
427   FunctionType *FT = cast<FunctionType>(
428     I.getCalledValue()->getType()->getContainedType(0));
429   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
430     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
431       Type* T = I.getArgOperand(i)->getType();
432       for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
433            i != e; ++i) {
434         if (i->isFloatingPointTy()) {
435           MMI->setUsesVAFloatArgument(true);
436           return;
437         }
438       }
439     }
440   }
441 }
442
443 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
444 /// call, and add them to the specified machine basic block.
445 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
446                         MachineBasicBlock *MBB) {
447   // Inform the MachineModuleInfo of the personality for this landing pad.
448   const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
449   assert(CE->getOpcode() == Instruction::BitCast &&
450          isa<Function>(CE->getOperand(0)) &&
451          "Personality should be a function");
452   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
453
454   // Gather all the type infos for this landing pad and pass them along to
455   // MachineModuleInfo.
456   std::vector<const GlobalVariable *> TyInfo;
457   unsigned N = I.getNumArgOperands();
458
459   for (unsigned i = N - 1; i > 1; --i) {
460     if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
461       unsigned FilterLength = CI->getZExtValue();
462       unsigned FirstCatch = i + FilterLength + !FilterLength;
463       assert(FirstCatch <= N && "Invalid filter length");
464
465       if (FirstCatch < N) {
466         TyInfo.reserve(N - FirstCatch);
467         for (unsigned j = FirstCatch; j < N; ++j)
468           TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
469         MMI->addCatchTypeInfo(MBB, TyInfo);
470         TyInfo.clear();
471       }
472
473       if (!FilterLength) {
474         // Cleanup.
475         MMI->addCleanup(MBB);
476       } else {
477         // Filter.
478         TyInfo.reserve(FilterLength - 1);
479         for (unsigned j = i + 1; j < FirstCatch; ++j)
480           TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
481         MMI->addFilterTypeInfo(MBB, TyInfo);
482         TyInfo.clear();
483       }
484
485       N = i;
486     }
487   }
488
489   if (N > 2) {
490     TyInfo.reserve(N - 2);
491     for (unsigned j = 2; j < N; ++j)
492       TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
493     MMI->addCatchTypeInfo(MBB, TyInfo);
494   }
495 }
496
497 /// AddLandingPadInfo - Extract the exception handling information from the
498 /// landingpad instruction and add them to the specified machine module info.
499 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
500                              MachineBasicBlock *MBB) {
501   MMI.addPersonality(MBB,
502                      cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
503
504   if (I.isCleanup())
505     MMI.addCleanup(MBB);
506
507   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
508   //        but we need to do it this way because of how the DWARF EH emitter
509   //        processes the clauses.
510   for (unsigned i = I.getNumClauses(); i != 0; --i) {
511     Value *Val = I.getClause(i - 1);
512     if (I.isCatch(i - 1)) {
513       MMI.addCatchTypeInfo(MBB,
514                            dyn_cast<GlobalVariable>(Val->stripPointerCasts()));
515     } else {
516       // Add filters in a list.
517       Constant *CVal = cast<Constant>(Val);
518       SmallVector<const GlobalVariable*, 4> FilterList;
519       for (User::op_iterator
520              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
521         FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts()));
522
523       MMI.addFilterTypeInfo(MBB, FilterList);
524     }
525   }
526 }