blob: c00b11893bfd6ea623695a52dd1f6ae19cf5cdc7 [file] [log] [blame]
Dan Gohmana3624b62009-11-23 17:16:22 +00001//===-- 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
Dan Gohmane7846162010-07-07 16:01:37 +000015#include "llvm/CodeGen/FunctionLoweringInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#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"
David Majnemercde33032015-03-30 22:58:10 +000023#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000025#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#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"
Dan Gohmana3624b62009-11-23 17:16:22 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/Support/raw_ostream.h"
Hans Wennborgacb842d2014-03-05 02:43:26 +000036#include "llvm/Target/TargetFrameLowering.h"
Chandler Carruth92051402014-03-05 10:30:38 +000037#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Target/TargetLowering.h"
39#include "llvm/Target/TargetOptions.h"
40#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohmana3624b62009-11-23 17:16:22 +000042#include <algorithm>
43using namespace llvm;
44
Chandler Carruth1b9dde02014-04-22 02:02:50 +000045#define DEBUG_TYPE "function-lowering-info"
46
Dan Gohmana3624b62009-11-23 17:16:22 +000047/// 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.
Dan Gohman913c9982010-04-15 04:33:49 +000050static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
Dan Gohman7c845e42010-04-20 14:50:13 +000051 if (I->use_empty()) return false;
Dan Gohmana3624b62009-11-23 17:16:22 +000052 if (isa<PHINode>(I)) return true;
Dan Gohman913c9982010-04-15 04:33:49 +000053 const BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +000054 for (const User *U : I->users())
Gabor Greif52617fc2010-07-09 16:08:33 +000055 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
Dan Gohmana3624b62009-11-23 17:16:22 +000056 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +000057
Dan Gohmana3624b62009-11-23 17:16:22 +000058 return false;
59}
60
Jiangning Liuffbc6902014-09-19 05:30:35 +000061static 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
David Majnemercde33032015-03-30 22:58:10 +000083namespace {
84struct WinEHNumbering {
85 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo), NextState(0) {}
86
87 WinEHFuncInfo &FuncInfo;
88 int NextState;
89
90 SmallVector<ActionHandler *, 4> HandlerStack;
91
92 int currentEHNumber() const {
93 return HandlerStack.empty() ? -1 : HandlerStack.back()->getEHState();
94 }
95
96 void parseEHActions(const IntrinsicInst *II,
97 SmallVectorImpl<ActionHandler *> &Actions);
98 void createUnwindMapEntry(int ToState, ActionHandler *AH);
99 void proccessCallSite(ArrayRef<ActionHandler *> Actions, ImmutableCallSite CS);
100 void calculateStateNumbers(const Function &F);
101};
102}
103
Hans Wennborgacb842d2014-03-05 02:43:26 +0000104void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
105 SelectionDAG *DAG) {
Dan Gohmana3624b62009-11-23 17:16:22 +0000106 Fn = &fn;
107 MF = &mf;
Eric Christopher2ae2de72014-10-09 00:57:31 +0000108 TLI = MF->getSubtarget().getTargetLowering();
Dan Gohmana3624b62009-11-23 17:16:22 +0000109 RegInfo = &MF->getRegInfo();
David Majnemercde33032015-03-30 22:58:10 +0000110 MachineModuleInfo &MMI = MF->getMMI();
Dan Gohmana3624b62009-11-23 17:16:22 +0000111
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000112 // Check whether the function can return without sret-demotion.
113 SmallVector<ISD::OutputArg, 4> Outs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000114 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
115 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
Eric Christopher2ae2de72014-10-09 00:57:31 +0000116 Fn->isVarArg(), Outs, Fn->getContext());
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000117
Dan Gohmana3624b62009-11-23 17:16:22 +0000118 // Initialize the mapping of values to registers. This is only set up for
119 // instruction values that are used outside of the block that defines
120 // them.
Dan Gohman913c9982010-04-15 04:33:49 +0000121 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
Dan Gohmana3624b62009-11-23 17:16:22 +0000122 for (; BB != EB; ++BB)
Eric Christopher219d51d2012-02-24 01:59:01 +0000123 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
124 I != E; ++I) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000125 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000126 // Static allocas can be folded into the initial stack frame adjustment.
127 if (AI->isStaticAlloca()) {
128 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
129 Type *Ty = AI->getAllocatedType();
130 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
131 unsigned Align =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000132 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
133 AI->getAlignment());
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000134
135 TySize *= CUI->getZExtValue(); // Get total allocated size.
136 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
137
138 StaticAllocaMap[AI] =
139 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
140
141 } else {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000142 unsigned Align = std::max(
143 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
144 AI->getAllocatedType()),
145 AI->getAlignment());
Eric Christopherd9134482014-08-04 21:25:23 +0000146 unsigned StackAlign =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000147 MF->getSubtarget().getFrameLowering()->getStackAlignment();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000148 if (Align <= StackAlign)
149 Align = 0;
150 // Inform the Frame Information that we have variable-sized objects.
151 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
152 }
153 }
154
155 // Look for inline asm that clobbers the SP register.
156 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
157 ImmutableCallSite CS(I);
Hans Wennborg0c72fd22014-03-05 03:21:23 +0000158 if (isa<InlineAsm>(CS.getCalledValue())) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000159 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Eric Christopher11e4df72015-02-26 22:38:43 +0000160 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000161 std::vector<TargetLowering::AsmOperandInfo> Ops =
Eric Christopher11e4df72015-02-26 22:38:43 +0000162 TLI->ParseConstraints(TRI, CS);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000163 for (size_t I = 0, E = Ops.size(); I != E; ++I) {
164 TargetLowering::AsmOperandInfo &Op = Ops[I];
165 if (Op.Type == InlineAsm::isClobber) {
166 // Clobbers don't have SDValue operands, hence SDValue().
167 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
Eric Christopher2ae2de72014-10-09 00:57:31 +0000168 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
Eric Christopher11e4df72015-02-26 22:38:43 +0000169 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
170 Op.ConstraintVT);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000171 if (PhysReg.first == SP)
172 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
173 }
174 }
175 }
176 }
177
Reid Kleckner2d9bb652014-08-22 21:59:26 +0000178 // Look for calls to the @llvm.va_start intrinsic. We can omit some
179 // prologue boilerplate for variadic functions that don't examine their
180 // arguments.
181 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
182 if (II->getIntrinsicID() == Intrinsic::vastart)
183 MF->getFrameInfo()->setHasVAStart(true);
184 }
185
Reid Kleckner16e55412014-08-29 21:42:08 +0000186 // If we have a musttail call in a variadic funciton, we need to ensure we
187 // forward implicit register parameters.
Reid Klecknerdccd0cb2014-08-29 21:42:21 +0000188 if (const auto *CI = dyn_cast<CallInst>(I)) {
Reid Kleckner16e55412014-08-29 21:42:08 +0000189 if (CI->isMustTailCall() && Fn->isVarArg())
190 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
191 }
192
Dan Gohman1e9362772010-07-16 17:54:27 +0000193 // Mark values used outside their block as exported, by allocating
194 // a virtual register for them.
Cameron Zwarichf8b22b32011-02-22 03:24:52 +0000195 if (isUsedOutsideOfDefiningBlock(I))
Dan Gohmana3624b62009-11-23 17:16:22 +0000196 if (!isa<AllocaInst>(I) ||
197 !StaticAllocaMap.count(cast<AllocaInst>(I)))
198 InitializeRegForValue(I);
199
Dan Gohman1e9362772010-07-16 17:54:27 +0000200 // Collect llvm.dbg.declare information. This is done now instead of
201 // during the initial isel pass through the IR so that it is done
202 // in a predictable order.
203 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
Manman Ren983a16c2013-06-28 05:43:10 +0000204 DIVariable DIVar(DI->getVariable());
205 assert((!DIVar || DIVar.isVariable()) &&
206 "Variable in DbgDeclareInst should be either null or a DIVariable.");
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000207 if (MMI.hasDebugInfo() && DIVar && DI->getDebugLoc()) {
Dan Gohman1e9362772010-07-16 17:54:27 +0000208 // 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;
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000220 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
Dan Gohman1e9362772010-07-16 17:54:27 +0000221 FI, DI->getDebugLoc());
222 }
223 }
224 }
225 }
226 }
Jiangning Liuffbc6902014-09-19 05:30:35 +0000227
228 // Decide the preferred extend type for a value.
229 PreferredExtendType[I] = getPreferredExtendForValue(I);
Dan Gohman1e9362772010-07-16 17:54:27 +0000230 }
231
Dan Gohmana3624b62009-11-23 17:16:22 +0000232 // 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.
Dan Gohmanf57117d2010-04-14 16:30:40 +0000235 for (BB = Fn->begin(); BB != EB; ++BB) {
Dan Gohmana3624b62009-11-23 17:16:22 +0000236 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.
Dan Gohman0f055d32010-04-20 14:46:25 +0000248 for (BasicBlock::const_iterator I = BB->begin();
249 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
250 if (PN->use_empty()) continue;
Dan Gohmana3624b62009-11-23 17:16:22 +0000251
Rafael Espindolae53b7d12011-05-13 15:18:06 +0000252 // Skip empty types
253 if (PN->getType()->isEmptyTy())
254 continue;
255
Dan Gohman7b7f0882010-04-20 14:48:02 +0000256 DebugLoc DL = PN->getDebugLoc();
Dan Gohmana3624b62009-11-23 17:16:22 +0000257 unsigned PHIReg = ValueMap[PN];
258 assert(PHIReg && "PHI node does not have an assigned virtual register!");
259
260 SmallVector<EVT, 4> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000261 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000262 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
263 EVT VT = ValueVTs[vti];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000264 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
Eric Christopherfc6de422014-08-05 02:39:49 +0000265 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Dan Gohmana3624b62009-11-23 17:16:22 +0000266 for (unsigned i = 0; i != NumRegisters; ++i)
Chris Lattnerb06015a2010-02-09 19:54:29 +0000267 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
Dan Gohmana3624b62009-11-23 17:16:22 +0000268 PHIReg += NumRegisters;
269 }
270 }
271 }
Dan Gohman69e8e322010-04-14 16:32:56 +0000272
273 // Mark landing pad blocks.
274 for (BB = Fn->begin(); BB != EB; ++BB)
David Majnemercde33032015-03-30 22:58:10 +0000275 if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
Dan Gohman69e8e322010-04-14 16:32:56 +0000276 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
David Majnemercde33032015-03-30 22:58:10 +0000277
278 // Calculate EH numbers for WinEH.
279 if (fn.getFnAttribute("wineh-parent").getValueAsString() == fn.getName())
280 WinEHNumbering(MMI.getWinEHFuncInfo(&fn)).calculateStateNumbers(fn);
281}
282
283void WinEHNumbering::parseEHActions(const IntrinsicInst *II,
284 SmallVectorImpl<ActionHandler *> &Actions) {
285 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
286 uint64_t ActionKind =
287 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
288 if (ActionKind == /*catch=*/1) {
289 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
290 Value *CatchObject = II->getArgOperand(I + 2);
291 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
292 I += 4;
293 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
294 CH->setExceptionVar(CatchObject);
295 CH->setHandlerBlockOrFunc(Handler);
296 Actions.push_back(CH);
297 } else {
298 assert(ActionKind == 0 && "expected a cleanup or a catch action!");
299 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
300 I += 2;
301 auto *CH = new CleanupHandler(/*BB=*/nullptr);
302 CH->setHandlerBlockOrFunc(Handler);
303 Actions.push_back(CH);
304 }
305 }
306 std::reverse(Actions.begin(), Actions.end());
307}
308
309void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
310 WinEHUnwindMapEntry UME;
311 UME.ToState = ToState;
312 if (auto *CH = dyn_cast<CleanupHandler>(AH))
313 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
314 else
315 UME.Cleanup = nullptr;
316 FuncInfo.UnwindMap.push_back(UME);
317}
318
319static void print_name(const Value *V) {
David Majnemer9a555392015-03-30 23:14:45 +0000320#ifndef NDEBUG
David Majnemercde33032015-03-30 22:58:10 +0000321 if (!V) {
322 DEBUG(dbgs() << "null");
323 return;
324 }
325
326 if (const auto *F = dyn_cast<Function>(V))
327 DEBUG(dbgs() << F->getName());
328 else
329 DEBUG(V->dump());
David Majnemer9a555392015-03-30 23:14:45 +0000330#endif
David Majnemercde33032015-03-30 22:58:10 +0000331}
332
333void WinEHNumbering::proccessCallSite(ArrayRef<ActionHandler *> Actions,
334 ImmutableCallSite CS) {
335 // float, int
336 // float, double, int
337 int FirstMismatch = 0;
338 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
339 ++FirstMismatch) {
340 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
341 Actions[FirstMismatch]->getHandlerBlockOrFunc())
342 break;
343 delete Actions[FirstMismatch];
344 }
345
346 // Don't recurse while we are looping over the handler stack. Instead, defer
347 // the numbering of the catch handlers until we are done popping.
348 SmallVector<const Function *, 4> UnnumberedHandlers;
349 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
350 if (auto *CH = dyn_cast<CatchHandler>(HandlerStack.back()))
351 if (const auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc()))
352 UnnumberedHandlers.push_back(F);
353 // Pop the handlers off of the stack.
354 delete HandlerStack.back();
355 HandlerStack.pop_back();
356 }
357
358 for (const Function *F : UnnumberedHandlers)
359 calculateStateNumbers(*F);
360
361 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
362 createUnwindMapEntry(currentEHNumber(), Actions[I]);
363 Actions[I]->setEHState(NextState++);
364 DEBUG(dbgs() << "Creating unwind map entry for: (");
365 print_name(Actions[I]->getHandlerBlockOrFunc());
366 DEBUG(dbgs() << ", " << currentEHNumber() << ")\n");
367 HandlerStack.push_back(Actions[I]);
368 }
369
370 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
371 print_name(CS ? CS.getCalledValue() : nullptr);
372 DEBUG(dbgs() << '\n');
373}
374
375void WinEHNumbering::calculateStateNumbers(const Function &F) {
376 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
377 SmallVector<ActionHandler *, 4> ActionList;
378 for (const BasicBlock &BB : F) {
379 for (const Instruction &I : BB) {
380 const auto *CI = dyn_cast<CallInst>(&I);
381 if (!CI || CI->doesNotThrow())
382 continue;
383 proccessCallSite(None, CI);
384 }
385 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
386 if (!II)
387 continue;
388 const LandingPadInst *LPI = II->getLandingPadInst();
389 if (auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode())) {
390 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
391 parseEHActions(ActionsCall, ActionList);
392 proccessCallSite(ActionList, II);
393 ActionList.clear();
394 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
395 }
396 }
397 proccessCallSite(None, ImmutableCallSite());
Dan Gohmana3624b62009-11-23 17:16:22 +0000398}
399
400/// clear - Clear out all the function-specific state. This returns this
401/// FunctionLoweringInfo to an empty state, ready to be used for a
402/// different function.
403void FunctionLoweringInfo::clear() {
Dan Gohmanad0b3ea2010-04-14 17:11:23 +0000404 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
405 "Not all catch info was assigned to a landing pad!");
406
Dan Gohmana3624b62009-11-23 17:16:22 +0000407 MBBMap.clear();
408 ValueMap.clear();
409 StaticAllocaMap.clear();
410#ifndef NDEBUG
411 CatchInfoLost.clear();
412 CatchInfoFound.clear();
413#endif
414 LiveOutRegInfo.clear();
Cameron Zwarich988faf92011-02-24 10:00:13 +0000415 VisitedBBs.clear();
Evan Cheng6e822452010-04-28 23:08:54 +0000416 ArgDbgValues.clear();
Devang Patel86ec8b32010-08-31 22:22:42 +0000417 ByValArgFrameIndexMap.clear();
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000418 RegFixups.clear();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000419 StatepointStackSlots.clear();
Jiangning Liu3b096172014-09-24 03:22:56 +0000420 PreferredExtendType.clear();
Dan Gohmana3624b62009-11-23 17:16:22 +0000421}
422
Dan Gohman93f59202010-07-02 00:10:16 +0000423/// CreateReg - Allocate a single virtual register for the given type.
Patrik Hagglund5e6c3612012-12-13 06:34:11 +0000424unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
Eric Christopherd9134482014-08-04 21:25:23 +0000425 return RegInfo->createVirtualRegister(
Eric Christopher2ae2de72014-10-09 00:57:31 +0000426 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
Dan Gohmana3624b62009-11-23 17:16:22 +0000427}
428
Dan Gohman93f59202010-07-02 00:10:16 +0000429/// CreateRegs - Allocate the appropriate number of virtual registers of
Dan Gohmana3624b62009-11-23 17:16:22 +0000430/// the correctly promoted or expanded types. Assign these registers
431/// consecutive vreg numbers and return the first assigned number.
432///
433/// In the case that the given value has struct or array type, this function
434/// will assign registers for each member or element.
435///
Chris Lattner229907c2011-07-18 04:54:35 +0000436unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
Eric Christopher2ae2de72014-10-09 00:57:31 +0000437 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
Bill Wendling0ccf3102013-06-19 20:32:16 +0000438
Dan Gohmana3624b62009-11-23 17:16:22 +0000439 SmallVector<EVT, 4> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000440 ComputeValueVTs(*TLI, Ty, ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000441
442 unsigned FirstReg = 0;
443 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
444 EVT ValueVT = ValueVTs[Value];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000445 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000446
Bill Wendling8db01cb2013-06-06 00:11:39 +0000447 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000448 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman93f59202010-07-02 00:10:16 +0000449 unsigned R = CreateReg(RegisterVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000450 if (!FirstReg) FirstReg = R;
451 }
452 }
453 return FirstReg;
454}
Dan Gohmanad97b3d2009-11-23 17:42:46 +0000455
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000456/// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
457/// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
458/// the register's LiveOutInfo is for a smaller bit width, it is extended to
459/// the larger bit width by zero extension. The bit width must be no smaller
460/// than the LiveOutInfo's existing bit width.
461const FunctionLoweringInfo::LiveOutInfo *
462FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
463 if (!LiveOutRegInfo.inBounds(Reg))
Craig Topperc0196b12014-04-14 00:51:57 +0000464 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000465
466 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
467 if (!LOI->IsValid)
Craig Topperc0196b12014-04-14 00:51:57 +0000468 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000469
Cameron Zwarichd2f30412011-02-25 01:10:55 +0000470 if (BitWidth > LOI->KnownZero.getBitWidth()) {
Cameron Zwarich4c82cd22011-02-25 01:11:01 +0000471 LOI->NumSignBits = 1;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000472 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
473 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
474 }
475
476 return LOI;
477}
478
479/// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
480/// register based on the LiveOutInfo of its operands.
481void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
Chris Lattner229907c2011-07-18 04:54:35 +0000482 Type *Ty = PN->getType();
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000483 if (!Ty->isIntegerTy() || Ty->isVectorTy())
484 return;
485
486 SmallVector<EVT, 1> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000487 ComputeValueVTs(*TLI, Ty, ValueVTs);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000488 assert(ValueVTs.size() == 1 &&
489 "PHIs with non-vector integer types should have a single VT.");
490 EVT IntVT = ValueVTs[0];
491
Bill Wendling8db01cb2013-06-06 00:11:39 +0000492 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000493 return;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000494 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000495 unsigned BitWidth = IntVT.getSizeInBits();
496
497 unsigned DestReg = ValueMap[PN];
498 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
499 return;
500 LiveOutRegInfo.grow(DestReg);
501 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
502
503 Value *V = PN->getIncomingValue(0);
504 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
505 DestLOI.NumSignBits = 1;
506 APInt Zero(BitWidth, 0);
507 DestLOI.KnownZero = Zero;
508 DestLOI.KnownOne = Zero;
509 return;
510 }
511
512 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
513 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
514 DestLOI.NumSignBits = Val.getNumSignBits();
515 DestLOI.KnownZero = ~Val;
516 DestLOI.KnownOne = Val;
517 } else {
518 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
519 "CopyToReg node was created.");
520 unsigned SrcReg = ValueMap[V];
521 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
522 DestLOI.IsValid = false;
523 return;
524 }
525 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
526 if (!SrcLOI) {
527 DestLOI.IsValid = false;
528 return;
529 }
530 DestLOI = *SrcLOI;
531 }
532
533 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
534 DestLOI.KnownOne.getBitWidth() == BitWidth &&
535 "Masks should have the same bit width as the type.");
536
537 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
538 Value *V = PN->getIncomingValue(i);
539 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
540 DestLOI.NumSignBits = 1;
541 APInt Zero(BitWidth, 0);
542 DestLOI.KnownZero = Zero;
543 DestLOI.KnownOne = Zero;
Eric Christopher0713a9d2011-06-08 23:55:35 +0000544 return;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000545 }
546
547 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
548 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
549 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
550 DestLOI.KnownZero &= ~Val;
551 DestLOI.KnownOne &= Val;
552 continue;
553 }
554
555 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
556 "its CopyToReg node was created.");
557 unsigned SrcReg = ValueMap[V];
558 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
559 DestLOI.IsValid = false;
560 return;
561 }
562 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
563 if (!SrcLOI) {
564 DestLOI.IsValid = false;
565 return;
566 }
567 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
568 DestLOI.KnownZero &= SrcLOI->KnownZero;
569 DestLOI.KnownOne &= SrcLOI->KnownOne;
570 }
571}
572
Devang Patel9d904e12011-09-08 22:59:09 +0000573/// setArgumentFrameIndex - Record frame index for the byval
Devang Patel86ec8b32010-08-31 22:22:42 +0000574/// argument. This overrides previous frame index entry for this argument,
575/// if any.
Devang Patel9d904e12011-09-08 22:59:09 +0000576void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
Eric Christopher219d51d2012-02-24 01:59:01 +0000577 int FI) {
Devang Patel86ec8b32010-08-31 22:22:42 +0000578 ByValArgFrameIndexMap[A] = FI;
579}
Eric Christopher0713a9d2011-06-08 23:55:35 +0000580
Devang Patel9d904e12011-09-08 22:59:09 +0000581/// getArgumentFrameIndex - Get frame index for the byval argument.
Devang Patel86ec8b32010-08-31 22:22:42 +0000582/// If the argument does not have any assigned frame index then 0 is
583/// returned.
Devang Patel9d904e12011-09-08 22:59:09 +0000584int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
Eric Christopher0713a9d2011-06-08 23:55:35 +0000585 DenseMap<const Argument *, int>::iterator I =
Devang Patel86ec8b32010-08-31 22:22:42 +0000586 ByValArgFrameIndexMap.find(A);
587 if (I != ByValArgFrameIndexMap.end())
588 return I->second;
Eric Christopher18c6be72012-02-23 03:39:43 +0000589 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
Devang Patel86ec8b32010-08-31 22:22:42 +0000590 return 0;
591}
592
Michael J. Spencer8b98bf22012-02-22 19:06:13 +0000593/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
594/// being passed to this variadic function, and set the MachineModuleInfo's
595/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
596/// reference to _fltused on Windows, which will link in MSVCRT's
597/// floating-point support.
598void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
599 MachineModuleInfo *MMI)
600{
601 FunctionType *FT = cast<FunctionType>(
602 I.getCalledValue()->getType()->getContainedType(0));
603 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
604 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
605 Type* T = I.getArgOperand(i)->getType();
606 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
607 i != e; ++i) {
608 if (i->isFloatingPointTy()) {
609 MMI->setUsesVAFloatArgument(true);
610 return;
611 }
612 }
613 }
614 }
615}
616
Bill Wendling247fd3b2011-08-17 21:56:44 +0000617/// AddLandingPadInfo - Extract the exception handling information from the
618/// landingpad instruction and add them to the specified machine module info.
619void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
620 MachineBasicBlock *MBB) {
621 MMI.addPersonality(MBB,
622 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
623
624 if (I.isCleanup())
625 MMI.addCleanup(MBB);
626
627 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
628 // but we need to do it this way because of how the DWARF EH emitter
629 // processes the clauses.
630 for (unsigned i = I.getNumClauses(); i != 0; --i) {
631 Value *Val = I.getClause(i - 1);
632 if (I.isCatch(i - 1)) {
633 MMI.addCatchTypeInfo(MBB,
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000634 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000635 } else {
636 // Add filters in a list.
637 Constant *CVal = cast<Constant>(Val);
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000638 SmallVector<const GlobalValue*, 4> FilterList;
Bill Wendling247fd3b2011-08-17 21:56:44 +0000639 for (User::op_iterator
640 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000641 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000642
643 MMI.addFilterTypeInfo(MBB, FilterList);
644 }
645 }
646}