blob: c35f02a06ca117c14a2b299264396c951a00f2ec [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000027#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner90f42382006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattner975f5c92005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000057#else
Chris Lattneref598052006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Jim Laskey29e635d2006-08-02 12:30:23 +000061
62//===---------------------------------------------------------------------===//
63///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000074namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey03593f72006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner6f87d182006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000134 };
135}
Evan Chengc1e1d972006-01-23 07:01:07 +0000136
Chris Lattner7a60d912005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000174 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukman835702a2005-04-21 22:36:52 +0000190
Chris Lattner49409cb2006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattner6871b232005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner7a60d912005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000247 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000249
Reid Spencere0fc4df2006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000254 }
255
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
262
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MBBMap[BB] = MBB;
269 MF.getBasicBlockList().push_back(MBB);
270
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272 // appropriate.
273 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
276
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
281 else {
282 MVT::ValueType VT1,VT2;
283 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000284 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000285 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000286 }
Chris Lattner84a03502006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000292 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner49409cb2006-03-16 19:51:18 +0000296/// CreateRegForValue - Allocate the appropriate number of virtual registers of
297/// the correctly promoted or expanded types. Assign these registers
298/// consecutive vreg numbers and return the first assigned number.
299unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
301
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
305
Reid Spencer09575ba2007-02-15 03:39:18 +0000306 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000309 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000323 }
324
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
328 if (NV == 1) {
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
336 return Reg;
337 }
338
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner7a60d912005-01-07 07:47:53 +0000347
348//===----------------------------------------------------------------------===//
349/// SelectionDAGLowering - This is the common target-independent lowering
350/// implementation that is parameterized by a TargetLowering object.
351/// Also, targets can overload any lowering method.
352///
353namespace llvm {
354class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
356
Chris Lattner79084302007-02-04 01:31:47 +0000357 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000358
Chris Lattner4d9651c2005-01-17 22:19:26 +0000359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
362 /// analysis.
363 std::vector<SDOperand> PendingLoads;
364
Nate Begemaned728c12006-03-27 01:32:24 +0000365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
370
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
373 struct CaseRec {
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
381 Constant *LT;
382 Constant *GE;
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
385 CaseRange Range;
386 };
387
388 /// The comparison function for sorting Case values.
389 struct CaseCmp {
390 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere63b6512006-12-31 05:55:36 +0000391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Chris Lattner2fbff4d2007-02-13 20:09:07 +0000392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000394 }
395 };
396
Chris Lattner7a60d912005-01-07 07:47:53 +0000397public:
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
401 TargetLowering &TLI;
402 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000403 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000404
Nate Begemaned728c12006-03-27 01:32:24 +0000405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000408 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000409
Chris Lattner7a60d912005-01-07 07:47:53 +0000410 /// FuncInfo - Information about the function as a whole.
411 ///
412 FunctionLoweringInfo &FuncInfo;
413
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000415 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000417 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000418 }
419
Chris Lattner4108bb02005-01-17 19:43:36 +0000420 /// getRoot - Return the current virtual root of the Selection DAG.
421 ///
422 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000423 if (PendingLoads.empty())
424 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000425
Chris Lattner4d9651c2005-01-17 22:19:26 +0000426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
428 DAG.setRoot(Root);
429 PendingLoads.clear();
430 return Root;
431 }
432
433 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000436 PendingLoads.clear();
437 DAG.setRoot(Root);
438 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000439 }
440
Chris Lattnered0110b2006-10-27 21:36:01 +0000441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
Chris Lattner7a60d912005-01-07 07:47:53 +0000443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000448 switch (Opcode) {
449 default: assert(0 && "Unknown instruction type encountered!");
450 abort();
451 // Build the switch statement using the Instruction.def file.
452#define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454#include "llvm/Instruction.def"
455 }
456 }
457
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
Chris Lattner4024c002006-03-15 22:19:46 +0000460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000461 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000462 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000463
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
466 }
467
Chris Lattner8471b152006-03-16 19:57:50 +0000468 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000469
Chris Lattner79084302007-02-04 01:31:47 +0000470 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000473 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000474 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000475
Chris Lattner6f87d182006-02-22 22:37:12 +0000476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477 MVT::ValueType VT,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000481
Chris Lattnered0110b2006-10-27 21:36:01 +0000482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000486 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000487 void LowerCallTo(Instruction &I,
488 const Type *CalledValueTy, unsigned CallingConv,
489 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey504e9942007-02-22 15:38:06 +0000490
Chris Lattner7a60d912005-01-07 07:47:53 +0000491 // Terminator instructions.
492 void visitRet(ReturnInst &I);
493 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000494 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 void visitUnreachable(UnreachableInst &I) { /* noop */ }
496
Nate Begemaned728c12006-03-27 01:32:24 +0000497 // Helper for visitSwitch
498 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000499 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000500
Chris Lattner7a60d912005-01-07 07:47:53 +0000501 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000502 void visitInvoke(InvokeInst &I);
503 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000504
Reid Spencer2eadb532007-01-21 00:29:26 +0000505 void visitScalarBinary(User &I, unsigned OpCode);
506 void visitVectorBinary(User &I, unsigned OpCode);
507 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000508 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000509 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000510 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000511 visitVectorBinary(I, ISD::VADD);
512 else if (I.getType()->isFloatingPoint())
513 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000514 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000515 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000516 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000517 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000518 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000519 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000520 visitVectorBinary(I, ISD::VMUL);
521 else if (I.getType()->isFloatingPoint())
522 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000523 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000524 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000525 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000526 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
527 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
528 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
529 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
530 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
531 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
532 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
533 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
534 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
535 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000536 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
537 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000538 void visitICmp(User &I);
539 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000540 // Visit the conversion instructions
541 void visitTrunc(User &I);
542 void visitZExt(User &I);
543 void visitSExt(User &I);
544 void visitFPTrunc(User &I);
545 void visitFPExt(User &I);
546 void visitFPToUI(User &I);
547 void visitFPToSI(User &I);
548 void visitUIToFP(User &I);
549 void visitSIToFP(User &I);
550 void visitPtrToInt(User &I);
551 void visitIntToPtr(User &I);
552 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000553
Chris Lattner67271862006-03-29 00:11:43 +0000554 void visitExtractElement(User &I);
555 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000556 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000557
Chris Lattner7a60d912005-01-07 07:47:53 +0000558 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000559 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000560
561 void visitMalloc(MallocInst &I);
562 void visitFree(FreeInst &I);
563 void visitAlloca(AllocaInst &I);
564 void visitLoad(LoadInst &I);
565 void visitStore(StoreInst &I);
566 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
567 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000568 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000569 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000570 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000571
Chris Lattner7a60d912005-01-07 07:47:53 +0000572 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000573 void visitVAArg(VAArgInst &I);
574 void visitVAEnd(CallInst &I);
575 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000576
Chris Lattner875def92005-01-11 05:56:49 +0000577 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000578
579 void visitUserOp1(Instruction &I) {
580 assert(0 && "UserOp1 should not exist at instruction selection time!");
581 abort();
582 }
583 void visitUserOp2(Instruction &I) {
584 assert(0 && "UserOp2 should not exist at instruction selection time!");
585 abort();
586 }
587};
588} // end namespace llvm
589
Chris Lattner8471b152006-03-16 19:57:50 +0000590SDOperand SelectionDAGLowering::getValue(const Value *V) {
591 SDOperand &N = NodeMap[V];
592 if (N.Val) return N;
593
594 const Type *VTy = V->getType();
595 MVT::ValueType VT = TLI.getValueType(VTy);
596 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
597 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
598 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000599 SDOperand N1 = NodeMap[V];
600 assert(N1.Val && "visit didn't populate the ValueMap!");
601 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000602 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
603 return N = DAG.getGlobalAddress(GV, VT);
604 } else if (isa<ConstantPointerNull>(C)) {
605 return N = DAG.getConstant(0, TLI.getPointerTy());
606 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000607 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000608 return N = DAG.getNode(ISD::UNDEF, VT);
609
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000610 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000611 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000612 unsigned NumElements = PTy->getNumElements();
613 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
614
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000615 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000616 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
617
618 // Create a VConstant node with generic Vector type.
619 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
620 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000621 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
622 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000623 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
624 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000625 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000626 unsigned NumElements = PTy->getNumElements();
627 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000628
629 // Now that we know the number and type of the elements, push a
630 // Constant or ConstantFP node onto the ops list for each element of
631 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000632 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000633 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000634 for (unsigned i = 0; i != NumElements; ++i)
635 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000636 } else {
637 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
638 SDOperand Op;
639 if (MVT::isFloatingPoint(PVT))
640 Op = DAG.getConstantFP(0, PVT);
641 else
642 Op = DAG.getConstant(0, PVT);
643 Ops.assign(NumElements, Op);
644 }
645
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000646 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000647 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
648 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000649 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
650 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000651 } else {
652 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000653 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000654 }
655 }
656
657 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
658 std::map<const AllocaInst*, int>::iterator SI =
659 FuncInfo.StaticAllocaMap.find(AI);
660 if (SI != FuncInfo.StaticAllocaMap.end())
661 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
662 }
663
Chris Lattner289aa442007-02-04 01:35:11 +0000664 DenseMap<const Value*, unsigned>::iterator VMI =
Chris Lattner8471b152006-03-16 19:57:50 +0000665 FuncInfo.ValueMap.find(V);
666 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
667
668 unsigned InReg = VMI->second;
669
670 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000671 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000672 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000673 // Source must be expanded. This input value is actually coming from the
674 // register pair VMI->second and VMI->second+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000675 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
676 unsigned NumVals = TLI.getNumElements(VT);
677 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
678 if (NumVals == 1)
679 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
680 else {
681 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
682 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
683 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
684 }
685 } else {
686 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
687 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
688 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
689 N = MVT::isFloatingPoint(VT)
690 ? DAG.getNode(ISD::FP_ROUND, VT, N)
691 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000692 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000693 } else {
694 // Otherwise, if this is a vector, make it available as a generic vector
695 // here.
696 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000697 const VectorType *PTy = cast<VectorType>(VTy);
698 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000699 PTyLegalElementVT);
700
701 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000702 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000703 if (PTyElementVT == PTyLegalElementVT) {
704 // If the value types are legal, just VBUILD the CopyFromReg nodes.
705 for (unsigned i = 0; i != NE; ++i)
706 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
707 PTyElementVT));
708 } else if (PTyElementVT < PTyLegalElementVT) {
709 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
710 for (unsigned i = 0; i != NE; ++i) {
711 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
712 PTyElementVT);
713 if (MVT::isFloatingPoint(PTyElementVT))
714 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
715 else
716 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
717 Ops.push_back(Op);
718 }
719 } else {
720 // If the register was expanded, use BUILD_PAIR.
721 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
722 for (unsigned i = 0; i != NE/2; ++i) {
723 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
724 PTyElementVT);
725 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
726 PTyElementVT);
727 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
728 }
729 }
730
731 Ops.push_back(DAG.getConstant(NE, MVT::i32));
732 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000733 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000734
735 // Finally, use a VBIT_CONVERT to make this available as the appropriate
736 // vector type.
737 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
738 DAG.getConstant(PTy->getNumElements(),
739 MVT::i32),
740 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000741 }
742
743 return N;
744}
745
746
Chris Lattner7a60d912005-01-07 07:47:53 +0000747void SelectionDAGLowering::visitRet(ReturnInst &I) {
748 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000749 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000750 return;
751 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000752 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000753 NewValues.push_back(getRoot());
754 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
755 SDOperand RetOp = getValue(I.getOperand(i));
756
757 // If this is an integer return value, we need to promote it ourselves to
758 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
759 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000760 // FIXME: C calling convention requires the return type to be promoted to
761 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000762 if (MVT::isInteger(RetOp.getValueType()) &&
763 RetOp.getValueType() < MVT::i64) {
764 MVT::ValueType TmpVT;
765 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
766 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
767 else
768 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000769 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencere6f81872007-01-03 16:49:33 +0000770 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer0917adf2007-01-03 04:25:33 +0000771 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
772 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencere63b6512006-12-31 05:55:36 +0000773 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
774 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000775 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000776 }
777 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000778 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000779 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000780 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
781 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000782}
783
Chris Lattnered0110b2006-10-27 21:36:01 +0000784/// ExportFromCurrentBlock - If this condition isn't known to be exported from
785/// the current basic block, add it to ValueMap now so that we'll get a
786/// CopyTo/FromReg.
787void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
788 // No need to export constants.
789 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
790
791 // Already exported?
792 if (FuncInfo.isExportedInst(V)) return;
793
794 unsigned Reg = FuncInfo.InitializeRegForValue(V);
795 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
796}
797
Chris Lattner84a03502006-10-27 23:50:33 +0000798bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
799 const BasicBlock *FromBB) {
800 // The operands of the setcc have to be in this block. We don't know
801 // how to export them from some other block.
802 if (Instruction *VI = dyn_cast<Instruction>(V)) {
803 // Can export from current BB.
804 if (VI->getParent() == FromBB)
805 return true;
806
807 // Is already exported, noop.
808 return FuncInfo.isExportedInst(V);
809 }
810
811 // If this is an argument, we can export it if the BB is the entry block or
812 // if it is already exported.
813 if (isa<Argument>(V)) {
814 if (FromBB == &FromBB->getParent()->getEntryBlock())
815 return true;
816
817 // Otherwise, can only export this if it is already exported.
818 return FuncInfo.isExportedInst(V);
819 }
820
821 // Otherwise, constants can always be exported.
822 return true;
823}
824
Chris Lattnere60ae822006-10-29 21:01:20 +0000825static bool InBlock(const Value *V, const BasicBlock *BB) {
826 if (const Instruction *I = dyn_cast<Instruction>(V))
827 return I->getParent() == BB;
828 return true;
829}
830
Chris Lattnered0110b2006-10-27 21:36:01 +0000831/// FindMergedConditions - If Cond is an expression like
832void SelectionDAGLowering::FindMergedConditions(Value *Cond,
833 MachineBasicBlock *TBB,
834 MachineBasicBlock *FBB,
835 MachineBasicBlock *CurBB,
836 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000837 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000838 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000839
Reid Spencer266e42b2006-12-23 06:05:41 +0000840 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
841 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000842 BOp->getParent() != CurBB->getBasicBlock() ||
843 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
844 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000845 const BasicBlock *BB = CurBB->getBasicBlock();
846
Reid Spencer266e42b2006-12-23 06:05:41 +0000847 // If the leaf of the tree is a comparison, merge the condition into
848 // the caseblock.
849 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
850 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000851 // how to export them from some other block. If this is the first block
852 // of the sequence, no exporting is needed.
853 (CurBB == CurMBB ||
854 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
855 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000856 BOp = cast<Instruction>(Cond);
857 ISD::CondCode Condition;
858 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
859 switch (IC->getPredicate()) {
860 default: assert(0 && "Unknown icmp predicate opcode!");
861 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
862 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
863 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
864 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
865 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
866 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
867 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
868 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
869 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
870 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
871 }
872 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
873 ISD::CondCode FPC, FOC;
874 switch (FC->getPredicate()) {
875 default: assert(0 && "Unknown fcmp predicate opcode!");
876 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
877 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
878 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
879 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
880 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
881 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
882 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
883 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
884 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
885 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
886 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
887 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
888 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
889 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
890 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
891 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
892 }
893 if (FiniteOnlyFPMath())
894 Condition = FOC;
895 else
896 Condition = FPC;
897 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000898 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000899 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000900 }
901
Chris Lattnered0110b2006-10-27 21:36:01 +0000902 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
903 BOp->getOperand(1), TBB, FBB, CurBB);
904 SwitchCases.push_back(CB);
905 return;
906 }
907
908 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000909 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattnered0110b2006-10-27 21:36:01 +0000910 TBB, FBB, CurBB);
911 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000912 return;
913 }
914
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000915
916 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000917 MachineFunction::iterator BBI = CurBB;
918 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
919 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
920
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000921 if (Opc == Instruction::Or) {
922 // Codegen X | Y as:
923 // jmp_if_X TBB
924 // jmp TmpBB
925 // TmpBB:
926 // jmp_if_Y TBB
927 // jmp FBB
928 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000929
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000930 // Emit the LHS condition.
931 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
932
933 // Emit the RHS condition into TmpBB.
934 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
935 } else {
936 assert(Opc == Instruction::And && "Unknown merge op!");
937 // Codegen X & Y as:
938 // jmp_if_X TmpBB
939 // jmp FBB
940 // TmpBB:
941 // jmp_if_Y TBB
942 // jmp FBB
943 //
944 // This requires creation of TmpBB after CurBB.
945
946 // Emit the LHS condition.
947 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
948
949 // Emit the RHS condition into TmpBB.
950 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
951 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000952}
953
Chris Lattner427301f2006-10-31 22:37:42 +0000954/// If the set of cases should be emitted as a series of branches, return true.
955/// If we should emit this as a bunch of and/or'd together conditions, return
956/// false.
957static bool
958ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
959 if (Cases.size() != 2) return true;
960
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000961 // If this is two comparisons of the same values or'd or and'd together, they
962 // will get folded into a single comparison, so don't emit two blocks.
963 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
964 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
965 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
966 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
967 return false;
968 }
969
Chris Lattner427301f2006-10-31 22:37:42 +0000970 return true;
971}
972
Chris Lattner7a60d912005-01-07 07:47:53 +0000973void SelectionDAGLowering::visitBr(BranchInst &I) {
974 // Update machine-CFG edges.
975 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000976
977 // Figure out which block is immediately after the current one.
978 MachineBasicBlock *NextBlock = 0;
979 MachineFunction::iterator BBI = CurMBB;
980 if (++BBI != CurMBB->getParent()->end())
981 NextBlock = BBI;
982
983 if (I.isUnconditional()) {
984 // If this is not a fall-through branch, emit the branch.
985 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000986 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000987 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000988
Chris Lattner963ddad2006-10-24 17:57:59 +0000989 // Update machine-CFG edges.
990 CurMBB->addSuccessor(Succ0MBB);
991
992 return;
993 }
994
995 // If this condition is one of the special cases we handle, do special stuff
996 // now.
997 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +0000998 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +0000999
1000 // If this is a series of conditions that are or'd or and'd together, emit
1001 // this as a sequence of branches instead of setcc's with and/or operations.
1002 // For example, instead of something like:
1003 // cmp A, B
1004 // C = seteq
1005 // cmp D, E
1006 // F = setle
1007 // or C, F
1008 // jnz foo
1009 // Emit:
1010 // cmp A, B
1011 // je foo
1012 // cmp D, E
1013 // jle foo
1014 //
1015 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1016 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001017 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001018 BOp->getOpcode() == Instruction::Or)) {
1019 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001020 // If the compares in later blocks need to use values not currently
1021 // exported from this block, export them now. This block should always
1022 // be the first entry.
1023 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1024
Chris Lattner427301f2006-10-31 22:37:42 +00001025 // Allow some cases to be rejected.
1026 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001027 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1028 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1029 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1030 }
1031
1032 // Emit the branch for this block.
1033 visitSwitchCase(SwitchCases[0]);
1034 SwitchCases.erase(SwitchCases.begin());
1035 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001036 }
1037
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001038 // Okay, we decided not to do this, remove any inserted MBB's and clear
1039 // SwitchCases.
1040 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1041 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1042
Chris Lattner427301f2006-10-31 22:37:42 +00001043 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001044 }
1045 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001046
1047 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001048 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001049 Succ0MBB, Succ1MBB, CurMBB);
1050 // Use visitSwitchCase to actually insert the fast branch sequence for this
1051 // cond branch.
1052 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001053}
1054
Nate Begemaned728c12006-03-27 01:32:24 +00001055/// visitSwitchCase - Emits the necessary code to represent a single node in
1056/// the binary search tree resulting from lowering a switch instruction.
1057void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001058 SDOperand Cond;
1059 SDOperand CondLHS = getValue(CB.CmpLHS);
1060
Chris Lattnered0110b2006-10-27 21:36:01 +00001061 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1062 // handle common cases produced by branch lowering.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001063 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001064 Cond = CondLHS;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001065 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattnered0110b2006-10-27 21:36:01 +00001066 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1067 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1068 } else
1069 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001070
1071 // Set NextBlock to be the MBB immediately after the current one, if any.
1072 // This is used to avoid emitting unnecessary branches to the next block.
1073 MachineBasicBlock *NextBlock = 0;
1074 MachineFunction::iterator BBI = CurMBB;
1075 if (++BBI != CurMBB->getParent()->end())
1076 NextBlock = BBI;
1077
1078 // If the lhs block is the next block, invert the condition so that we can
1079 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001080 if (CB.TrueBB == NextBlock) {
1081 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001082 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1083 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1084 }
1085 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001086 DAG.getBasicBlock(CB.TrueBB));
1087 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001088 DAG.setRoot(BrCond);
1089 else
1090 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001091 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001092 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001093 CurMBB->addSuccessor(CB.TrueBB);
1094 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001095}
1096
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001097void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001098 // Emit the code for the jump table
1099 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001100 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1101 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1102 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1103 Table, Index));
1104 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001105}
1106
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001107void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1108 // Retrieve successors.
1109 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1110 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1111
1112 // Mark landing pad so that it doesn't get deleted in branch folding.
1113 LandingPad->setIsLandingPad();
1114
1115 // Insert a label before the invoke call to mark the try range.
1116 // This can be used to detect deletion of the invoke via the
1117 // MachineModuleInfo.
1118 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1119 unsigned BeginLabel = MMI->NextLabelID();
1120 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1121 DAG.getConstant(BeginLabel, MVT::i32)));
1122
Jim Laskey31fef782007-02-23 21:45:01 +00001123 LowerCallTo(I, I.getCalledValue()->getType(),
1124 I.getCallingConv(),
1125 false,
1126 getValue(I.getOperand(0)),
1127 3);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001128
1129 // Insert a label before the invoke call to mark the try range.
1130 // This can be used to detect deletion of the invoke via the
1131 // MachineModuleInfo.
1132 unsigned EndLabel = MMI->NextLabelID();
1133 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1134 DAG.getConstant(EndLabel, MVT::i32)));
1135
1136 // Inform MachineModuleInfo of range.
1137 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1138
1139 // Drop into normal successor.
1140 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1141 DAG.getBasicBlock(Return)));
1142
1143 // Update successor info
1144 CurMBB->addSuccessor(Return);
1145 CurMBB->addSuccessor(LandingPad);
1146}
1147
1148void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1149}
1150
Nate Begemaned728c12006-03-27 01:32:24 +00001151void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1152 // Figure out which block is immediately after the current one.
1153 MachineBasicBlock *NextBlock = 0;
1154 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001155
Nate Begemaned728c12006-03-27 01:32:24 +00001156 if (++BBI != CurMBB->getParent()->end())
1157 NextBlock = BBI;
1158
Chris Lattner6d6fc262006-10-22 21:36:53 +00001159 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1160
Nate Begemaned728c12006-03-27 01:32:24 +00001161 // If there is only the default destination, branch to it if it is not the
1162 // next basic block. Otherwise, just fall through.
1163 if (I.getNumOperands() == 2) {
1164 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001165
Nate Begemaned728c12006-03-27 01:32:24 +00001166 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001167 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001168 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001169 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001170
Chris Lattner6d6fc262006-10-22 21:36:53 +00001171 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001172 return;
1173 }
1174
1175 // If there are any non-default case statements, create a vector of Cases
1176 // representing each one, and sort the vector so that we can efficiently
1177 // create a binary search tree from them.
1178 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001179
Nate Begemaned728c12006-03-27 01:32:24 +00001180 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1181 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1182 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1183 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001184
Nate Begemaned728c12006-03-27 01:32:24 +00001185 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1186
1187 // Get the Value to be switched on and default basic blocks, which will be
1188 // inserted into CaseBlock records, representing basic blocks in the binary
1189 // search tree.
1190 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001191
1192 // Get the MachineFunction which holds the current MBB. This is used during
1193 // emission of jump tables, and when inserting any additional MBBs necessary
1194 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001195 MachineFunction *CurMF = CurMBB->getParent();
1196 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001197
1198 // If the switch has few cases (two or less) emit a series of specific
1199 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001200 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001201 // TODO: If any two of the cases has the same destination, and if one value
1202 // is the same as the other, but has one bit unset that the other has set,
1203 // use bit manipulation to do two compares at once. For example:
1204 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1205
Chris Lattner4c931502006-10-23 18:38:22 +00001206 // Rearrange the case blocks so that the last one falls through if possible.
1207 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1208 // The last case block won't fall through into 'NextBlock' if we emit the
1209 // branches in this order. See if rearranging a case value would help.
1210 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1211 if (Cases[i].second == NextBlock) {
1212 std::swap(Cases[i], Cases.back());
1213 break;
1214 }
1215 }
1216 }
1217
Chris Lattner6d6fc262006-10-22 21:36:53 +00001218 // Create a CaseBlock record representing a conditional branch to
1219 // the Case's target mbb if the value being switched on SV is equal
1220 // to C.
1221 MachineBasicBlock *CurBlock = CurMBB;
1222 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1223 MachineBasicBlock *FallThrough;
1224 if (i != e-1) {
1225 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1226 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1227 } else {
1228 // If the last case doesn't match, go to the default block.
1229 FallThrough = Default;
1230 }
1231
1232 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1233 Cases[i].second, FallThrough, CurBlock);
1234
1235 // If emitting the first comparison, just call visitSwitchCase to emit the
1236 // code into the current block. Otherwise, push the CaseBlock onto the
1237 // vector to be later processed by SDISel, and insert the node's MBB
1238 // before the next MBB.
1239 if (CurBlock == CurMBB)
1240 visitSwitchCase(CB);
1241 else
1242 SwitchCases.push_back(CB);
1243
1244 CurBlock = FallThrough;
1245 }
1246 return;
1247 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001248
Nate Begemand7a19102006-05-08 16:51:36 +00001249 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1250 // target supports indirect branches, then emit a jump table rather than
1251 // lowering the switch to a binary tree of conditional branches.
Evan Cheng84a28d42006-10-30 08:00:44 +00001252 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1253 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemandf488392006-05-03 03:48:02 +00001254 Cases.size() > 5) {
Chris Lattner1cf84d22007-02-14 07:18:16 +00001255 uint64_t First =cast<ConstantInt>(Cases.front().first)->getSExtValue();
1256 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getSExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001257 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1258
Nate Begemand7a19102006-05-08 16:51:36 +00001259 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001260 // Create a new basic block to hold the code for loading the address
1261 // of the jump table, and jumping to it. Update successor information;
1262 // we will either branch to the default case for the switch, or the jump
1263 // table.
1264 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1265 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1266 CurMBB->addSuccessor(Default);
1267 CurMBB->addSuccessor(JumpTableBB);
1268
1269 // Subtract the lowest switch case value from the value being switched on
1270 // and conditional branch to default mbb if the result is greater than the
1271 // difference between smallest and largest cases.
1272 SDOperand SwitchOp = getValue(SV);
1273 MVT::ValueType VT = SwitchOp.getValueType();
1274 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1275 DAG.getConstant(First, VT));
1276
1277 // The SDNode we just created, which holds the value being switched on
1278 // minus the the smallest case value, needs to be copied to a virtual
1279 // register so it can be used as an index into the jump table in a
1280 // subsequent basic block. This value may be smaller or larger than the
1281 // target's pointer type, and therefore require extension or truncating.
1282 if (VT > TLI.getPointerTy())
1283 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1284 else
1285 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001286
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001287 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1288 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1289
1290 // Emit the range check for the jump table, and branch to the default
1291 // block for the switch statement if the value being switched on exceeds
1292 // the largest case in the switch.
1293 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1294 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1295 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1296 DAG.getBasicBlock(Default)));
1297
Nate Begemandf488392006-05-03 03:48:02 +00001298 // Build a vector of destination BBs, corresponding to each target
1299 // of the jump table. If the value of the jump table slot corresponds to
1300 // a case statement, push the case's BB onto the vector, otherwise, push
1301 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001302 std::vector<MachineBasicBlock*> DestBBs;
Chris Lattnerab1812f2007-02-14 07:34:56 +00001303 int64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001304 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Chris Lattner1cf84d22007-02-14 07:18:16 +00001305 if (cast<ConstantInt>(ii->first)->getSExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001306 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001307 ++ii;
1308 } else {
1309 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001310 }
Nate Begemandf488392006-05-03 03:48:02 +00001311
Chris Lattner84a03502006-10-27 23:50:33 +00001312 // Update successor info. Add one edge to each unique successor.
1313 // Vector bool would be better, but vector<bool> is really slow.
1314 std::vector<unsigned char> SuccsHandled;
1315 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1316
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001317 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner84a03502006-10-27 23:50:33 +00001318 E = DestBBs.end(); I != E; ++I) {
1319 if (!SuccsHandled[(*I)->getNumber()]) {
1320 SuccsHandled[(*I)->getNumber()] = true;
1321 JumpTableBB->addSuccessor(*I);
1322 }
1323 }
Nate Begemandf488392006-05-03 03:48:02 +00001324
1325 // Create a jump table index for this jump table, or return an existing
1326 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001327 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1328
1329 // Set the jump table information so that we can codegen it as a second
1330 // MachineBasicBlock
1331 JT.Reg = JumpTableReg;
1332 JT.JTI = JTI;
1333 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001334 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001335 return;
1336 }
1337 }
Nate Begemaned728c12006-03-27 01:32:24 +00001338
1339 // Push the initial CaseRec onto the worklist
1340 std::vector<CaseRec> CaseVec;
1341 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1342
1343 while (!CaseVec.empty()) {
1344 // Grab a record representing a case range to process off the worklist
1345 CaseRec CR = CaseVec.back();
1346 CaseVec.pop_back();
1347
1348 // Size is the number of Cases represented by this range. If Size is 1,
1349 // then we are processing a leaf of the binary search tree. Otherwise,
1350 // we need to pick a pivot, and push left and right ranges onto the
1351 // worklist.
1352 unsigned Size = CR.Range.second - CR.Range.first;
1353
1354 if (Size == 1) {
1355 // Create a CaseBlock record representing a conditional branch to
1356 // the Case's target mbb if the value being switched on SV is equal
1357 // to C. Otherwise, branch to default.
1358 Constant *C = CR.Range.first->first;
1359 MachineBasicBlock *Target = CR.Range.first->second;
1360 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1361 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001362
Nate Begemaned728c12006-03-27 01:32:24 +00001363 // If the MBB representing the leaf node is the current MBB, then just
1364 // call visitSwitchCase to emit the code into the current block.
1365 // Otherwise, push the CaseBlock onto the vector to be later processed
1366 // by SDISel, and insert the node's MBB before the next MBB.
1367 if (CR.CaseBB == CurMBB)
1368 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001369 else
Nate Begemaned728c12006-03-27 01:32:24 +00001370 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001371 } else {
1372 // split case range at pivot
1373 CaseItr Pivot = CR.Range.first + (Size / 2);
1374 CaseRange LHSR(CR.Range.first, Pivot);
1375 CaseRange RHSR(Pivot, CR.Range.second);
1376 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001377 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001378
Nate Begemaned728c12006-03-27 01:32:24 +00001379 // We know that we branch to the LHS if the Value being switched on is
1380 // less than the Pivot value, C. We use this to optimize our binary
1381 // tree a bit, by recognizing that if SV is greater than or equal to the
1382 // LHS's Case Value, and that Case Value is exactly one less than the
1383 // Pivot's Value, then we can branch directly to the LHS's Target,
1384 // rather than creating a leaf node for it.
1385 if ((LHSR.second - LHSR.first) == 1 &&
1386 LHSR.first->first == CR.GE &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00001387 cast<ConstantInt>(C)->getZExtValue() ==
1388 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001389 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001390 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001391 TrueBB = new MachineBasicBlock(LLVMBB);
1392 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1393 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001394 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001395
Nate Begemaned728c12006-03-27 01:32:24 +00001396 // Similar to the optimization above, if the Value being switched on is
1397 // known to be less than the Constant CR.LT, and the current Case Value
1398 // is CR.LT - 1, then we can branch directly to the target block for
1399 // the current Case Value, rather than emitting a RHS leaf node for it.
1400 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00001401 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1402 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001403 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001404 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001405 FalseBB = new MachineBasicBlock(LLVMBB);
1406 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1407 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001408 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001409
Nate Begemaned728c12006-03-27 01:32:24 +00001410 // Create a CaseBlock record representing a conditional branch to
1411 // the LHS node if the value being switched on SV is less than C.
1412 // Otherwise, branch to LHS.
Chris Lattner1cf84d22007-02-14 07:18:16 +00001413 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1414 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001415
Nate Begemaned728c12006-03-27 01:32:24 +00001416 if (CR.CaseBB == CurMBB)
1417 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001418 else
Nate Begemaned728c12006-03-27 01:32:24 +00001419 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001420 }
1421 }
1422}
1423
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001424void SelectionDAGLowering::visitSub(User &I) {
1425 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001426 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001427 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001428 visitVectorBinary(I, ISD::VSUB);
1429 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001430 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1431 if (CFP->isExactlyValue(-0.0)) {
1432 SDOperand Op2 = getValue(I.getOperand(1));
1433 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1434 return;
1435 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001436 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001437 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001438 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001439}
1440
Reid Spencer2eadb532007-01-21 00:29:26 +00001441void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001442 SDOperand Op1 = getValue(I.getOperand(0));
1443 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001444
1445 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001446}
1447
Reid Spencer2eadb532007-01-21 00:29:26 +00001448void
1449SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001450 assert(isa<VectorType>(I.getType()));
1451 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001452 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001453
Reid Spencer2eadb532007-01-21 00:29:26 +00001454 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1455 getValue(I.getOperand(0)),
1456 getValue(I.getOperand(1)),
1457 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1458 Typ));
1459}
1460
1461void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1462 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001463 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001464 visitVectorBinary(I, VectorOp);
1465 else
1466 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001467}
Chris Lattner96c26752005-01-19 22:31:21 +00001468
Nate Begeman127321b2005-11-18 07:42:56 +00001469void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1470 SDOperand Op1 = getValue(I.getOperand(0));
1471 SDOperand Op2 = getValue(I.getOperand(1));
1472
Reid Spencer2341c222007-02-02 02:16:23 +00001473 if (TLI.getShiftAmountTy() < Op2.getValueType())
1474 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1475 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1476 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001477
Chris Lattner7a60d912005-01-07 07:47:53 +00001478 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1479}
1480
Reid Spencerd9436b62006-11-20 01:22:35 +00001481void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001482 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1483 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1484 predicate = IC->getPredicate();
1485 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1486 predicate = ICmpInst::Predicate(IC->getPredicate());
1487 SDOperand Op1 = getValue(I.getOperand(0));
1488 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001489 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001490 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001491 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1492 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1493 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1494 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1495 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1496 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1497 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1498 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1499 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1500 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1501 default:
1502 assert(!"Invalid ICmp predicate value");
1503 Opcode = ISD::SETEQ;
1504 break;
1505 }
1506 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1507}
1508
1509void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001510 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1511 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1512 predicate = FC->getPredicate();
1513 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1514 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001515 SDOperand Op1 = getValue(I.getOperand(0));
1516 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001517 ISD::CondCode Condition, FOC, FPC;
1518 switch (predicate) {
1519 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1520 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1521 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1522 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1523 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1524 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1525 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1526 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1527 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1528 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1529 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1530 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1531 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1532 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1533 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1534 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1535 default:
1536 assert(!"Invalid FCmp predicate value");
1537 FOC = FPC = ISD::SETFALSE;
1538 break;
1539 }
1540 if (FiniteOnlyFPMath())
1541 Condition = FOC;
1542 else
1543 Condition = FPC;
1544 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001545}
1546
1547void SelectionDAGLowering::visitSelect(User &I) {
1548 SDOperand Cond = getValue(I.getOperand(0));
1549 SDOperand TrueVal = getValue(I.getOperand(1));
1550 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001551 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00001552 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1553 TrueVal, FalseVal));
1554 } else {
1555 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1556 *(TrueVal.Val->op_end()-2),
1557 *(TrueVal.Val->op_end()-1)));
1558 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001559}
1560
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001561
1562void SelectionDAGLowering::visitTrunc(User &I) {
1563 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1564 SDOperand N = getValue(I.getOperand(0));
1565 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1566 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1567}
1568
1569void SelectionDAGLowering::visitZExt(User &I) {
1570 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1571 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1572 SDOperand N = getValue(I.getOperand(0));
1573 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1574 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1575}
1576
1577void SelectionDAGLowering::visitSExt(User &I) {
1578 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1579 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1580 SDOperand N = getValue(I.getOperand(0));
1581 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1582 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1583}
1584
1585void SelectionDAGLowering::visitFPTrunc(User &I) {
1586 // FPTrunc is never a no-op cast, no need to check
1587 SDOperand N = getValue(I.getOperand(0));
1588 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1589 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1590}
1591
1592void SelectionDAGLowering::visitFPExt(User &I){
1593 // FPTrunc is never a no-op cast, no need to check
1594 SDOperand N = getValue(I.getOperand(0));
1595 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1596 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1597}
1598
1599void SelectionDAGLowering::visitFPToUI(User &I) {
1600 // FPToUI is never a no-op cast, no need to check
1601 SDOperand N = getValue(I.getOperand(0));
1602 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1603 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1604}
1605
1606void SelectionDAGLowering::visitFPToSI(User &I) {
1607 // FPToSI is never a no-op cast, no need to check
1608 SDOperand N = getValue(I.getOperand(0));
1609 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1610 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1611}
1612
1613void SelectionDAGLowering::visitUIToFP(User &I) {
1614 // UIToFP is never a no-op cast, no need to check
1615 SDOperand N = getValue(I.getOperand(0));
1616 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1617 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1618}
1619
1620void SelectionDAGLowering::visitSIToFP(User &I){
1621 // UIToFP is never a no-op cast, no need to check
1622 SDOperand N = getValue(I.getOperand(0));
1623 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1624 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1625}
1626
1627void SelectionDAGLowering::visitPtrToInt(User &I) {
1628 // What to do depends on the size of the integer and the size of the pointer.
1629 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00001630 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001631 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001632 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001633 SDOperand Result;
1634 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1635 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1636 else
1637 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1638 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1639 setValue(&I, Result);
1640}
Chris Lattner7a60d912005-01-07 07:47:53 +00001641
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001642void SelectionDAGLowering::visitIntToPtr(User &I) {
1643 // What to do depends on the size of the integer and the size of the pointer.
1644 // We can either truncate, zero extend, or no-op, accordingly.
1645 SDOperand N = getValue(I.getOperand(0));
1646 MVT::ValueType SrcVT = N.getValueType();
1647 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1648 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1649 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1650 else
1651 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1652 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1653}
1654
1655void SelectionDAGLowering::visitBitCast(User &I) {
1656 SDOperand N = getValue(I.getOperand(0));
1657 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001658 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001659 // This is a cast to a vector from something else.
1660 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001661 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001662 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1663 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1664 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1665 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001666 return;
1667 }
1668 MVT::ValueType SrcVT = N.getValueType();
1669 if (SrcVT == MVT::Vector) {
1670 // This is a cast from a vctor to something else.
1671 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001672 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001673 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00001674 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001675
1676 // BitCast assures us that source and destination are the same size so this
1677 // is either a BIT_CONVERT or a no-op.
1678 if (DestVT != N.getValueType())
1679 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1680 else
1681 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00001682}
1683
Chris Lattner67271862006-03-29 00:11:43 +00001684void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001685 SDOperand InVec = getValue(I.getOperand(0));
1686 SDOperand InVal = getValue(I.getOperand(1));
1687 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1688 getValue(I.getOperand(2)));
1689
Chris Lattner29b23012006-03-19 01:17:20 +00001690 SDOperand Num = *(InVec.Val->op_end()-2);
1691 SDOperand Typ = *(InVec.Val->op_end()-1);
1692 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1693 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001694}
1695
Chris Lattner67271862006-03-29 00:11:43 +00001696void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001697 SDOperand InVec = getValue(I.getOperand(0));
1698 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1699 getValue(I.getOperand(1)));
1700 SDOperand Typ = *(InVec.Val->op_end()-1);
1701 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1702 TLI.getValueType(I.getType()), InVec, InIdx));
1703}
Chris Lattner32206f52006-03-18 01:44:44 +00001704
Chris Lattner098c01e2006-04-08 04:15:24 +00001705void SelectionDAGLowering::visitShuffleVector(User &I) {
1706 SDOperand V1 = getValue(I.getOperand(0));
1707 SDOperand V2 = getValue(I.getOperand(1));
1708 SDOperand Mask = getValue(I.getOperand(2));
1709
1710 SDOperand Num = *(V1.Val->op_end()-2);
1711 SDOperand Typ = *(V2.Val->op_end()-1);
1712 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1713 V1, V2, Mask, Num, Typ));
1714}
1715
1716
Chris Lattner7a60d912005-01-07 07:47:53 +00001717void SelectionDAGLowering::visitGetElementPtr(User &I) {
1718 SDOperand N = getValue(I.getOperand(0));
1719 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001720
1721 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1722 OI != E; ++OI) {
1723 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001724 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001725 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001726 if (Field) {
1727 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001728 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00001729 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001730 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001731 }
1732 Ty = StTy->getElementType(Field);
1733 } else {
1734 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001735
Chris Lattner43535a12005-11-09 04:45:33 +00001736 // If this is a constant subscript, handle it quickly.
1737 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001738 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00001739 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00001740 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001741 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1742 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001743 }
Chris Lattner43535a12005-11-09 04:45:33 +00001744
1745 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001746 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001747 SDOperand IdxN = getValue(Idx);
1748
1749 // If the index is smaller or larger than intptr_t, truncate or extend
1750 // it.
1751 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00001752 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00001753 } else if (IdxN.getValueType() > N.getValueType())
1754 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1755
1756 // If this is a multiply by a power of two, turn it into a shl
1757 // immediately. This is a very common case.
1758 if (isPowerOf2_64(ElementSize)) {
1759 unsigned Amt = Log2_64(ElementSize);
1760 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001761 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001762 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1763 continue;
1764 }
1765
1766 SDOperand Scale = getIntPtrConstant(ElementSize);
1767 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1768 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001769 }
1770 }
1771 setValue(&I, N);
1772}
1773
1774void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1775 // If this is a fixed sized alloca in the entry block of the function,
1776 // allocate it statically on the stack.
1777 if (FuncInfo.StaticAllocaMap.count(&I))
1778 return; // getValue will auto-populate this.
1779
1780 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001781 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00001782 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00001783 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00001784 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001785
1786 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001787 MVT::ValueType IntPtr = TLI.getPointerTy();
1788 if (IntPtr < AllocSize.getValueType())
1789 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1790 else if (IntPtr > AllocSize.getValueType())
1791 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001792
Chris Lattnereccb73d2005-01-22 23:04:37 +00001793 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001794 getIntPtrConstant(TySize));
1795
1796 // Handle alignment. If the requested alignment is less than or equal to the
1797 // stack alignment, ignore it and round the size of the allocation up to the
1798 // stack alignment size. If the size is greater than the stack alignment, we
1799 // note this in the DYNAMIC_STACKALLOC node.
1800 unsigned StackAlign =
1801 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1802 if (Align <= StackAlign) {
1803 Align = 0;
1804 // Add SA-1 to the size.
1805 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1806 getIntPtrConstant(StackAlign-1));
1807 // Mask out the low bits for alignment purposes.
1808 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1809 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1810 }
1811
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001812 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001813 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1814 MVT::Other);
1815 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00001816 setValue(&I, DSA);
1817 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001818
1819 // Inform the Frame Information that we have just allocated a variable-sized
1820 // object.
1821 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1822}
1823
Chris Lattner7a60d912005-01-07 07:47:53 +00001824void SelectionDAGLowering::visitLoad(LoadInst &I) {
1825 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001826
Chris Lattner4d9651c2005-01-17 22:19:26 +00001827 SDOperand Root;
1828 if (I.isVolatile())
1829 Root = getRoot();
1830 else {
1831 // Do not serialize non-volatile loads against each other.
1832 Root = DAG.getRoot();
1833 }
Chris Lattner4024c002006-03-15 22:19:46 +00001834
Evan Chenge71fe34d2006-10-09 20:57:25 +00001835 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001836 Root, I.isVolatile()));
1837}
1838
1839SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001840 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001841 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001842 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001843 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001844 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001845 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1846 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001847 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00001848 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001849 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001850
Chris Lattner4024c002006-03-15 22:19:46 +00001851 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001852 DAG.setRoot(L.getValue(1));
1853 else
1854 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001855
1856 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001857}
1858
1859
1860void SelectionDAGLowering::visitStore(StoreInst &I) {
1861 Value *SrcV = I.getOperand(0);
1862 SDOperand Src = getValue(SrcV);
1863 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00001864 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00001865 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001866}
1867
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001868/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1869/// access memory and has no other side effects at all.
1870static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1871#define GET_NO_MEMORY_INTRINSICS
1872#include "llvm/Intrinsics.gen"
1873#undef GET_NO_MEMORY_INTRINSICS
1874 return false;
1875}
1876
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001877// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1878// have any side-effects or if it only reads memory.
1879static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1880#define GET_SIDE_EFFECT_INFO
1881#include "llvm/Intrinsics.gen"
1882#undef GET_SIDE_EFFECT_INFO
1883 return false;
1884}
1885
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001886/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1887/// node.
1888void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1889 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001890 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001891 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001892
1893 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001894 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001895 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1896 if (OnlyLoad) {
1897 // We don't need to serialize loads against other loads.
1898 Ops.push_back(DAG.getRoot());
1899 } else {
1900 Ops.push_back(getRoot());
1901 }
1902 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001903
1904 // Add the intrinsic ID as an integer operand.
1905 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1906
1907 // Add all operands of the call to the operand list.
1908 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1909 SDOperand Op = getValue(I.getOperand(i));
1910
Reid Spencer09575ba2007-02-15 03:39:18 +00001911 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001912 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001913 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001914 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1915
1916 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1917 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1918 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1919 }
1920
1921 assert(TLI.isTypeLegal(Op.getValueType()) &&
1922 "Intrinsic uses a non-legal type?");
1923 Ops.push_back(Op);
1924 }
1925
1926 std::vector<MVT::ValueType> VTs;
1927 if (I.getType() != Type::VoidTy) {
1928 MVT::ValueType VT = TLI.getValueType(I.getType());
1929 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001930 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001931 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1932
1933 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1934 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1935 }
1936
1937 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1938 VTs.push_back(VT);
1939 }
1940 if (HasChain)
1941 VTs.push_back(MVT::Other);
1942
Chris Lattnerbd887772006-08-14 23:53:35 +00001943 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1944
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001945 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001946 SDOperand Result;
1947 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001948 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1949 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001950 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001951 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1952 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001953 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001954 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1955 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001956
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001957 if (HasChain) {
1958 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1959 if (OnlyLoad)
1960 PendingLoads.push_back(Chain);
1961 else
1962 DAG.setRoot(Chain);
1963 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001964 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001965 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001966 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1967 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1968 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1969 DAG.getValueType(EVT));
1970 }
1971 setValue(&I, Result);
1972 }
1973}
1974
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001975/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1976/// we want to emit this as a call to a named external function, return the name
1977/// otherwise lower it and return null.
1978const char *
1979SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1980 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001981 default:
1982 // By default, turn this into a target intrinsic node.
1983 visitTargetIntrinsic(I, Intrinsic);
1984 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001985 case Intrinsic::vastart: visitVAStart(I); return 0;
1986 case Intrinsic::vaend: visitVAEnd(I); return 0;
1987 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00001988 case Intrinsic::returnaddress:
1989 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1990 getValue(I.getOperand(1))));
1991 return 0;
1992 case Intrinsic::frameaddress:
1993 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
1994 getValue(I.getOperand(1))));
1995 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001996 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00001997 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001998 break;
1999 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002000 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002001 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002002 case Intrinsic::memcpy_i32:
2003 case Intrinsic::memcpy_i64:
2004 visitMemIntrinsic(I, ISD::MEMCPY);
2005 return 0;
2006 case Intrinsic::memset_i32:
2007 case Intrinsic::memset_i64:
2008 visitMemIntrinsic(I, ISD::MEMSET);
2009 return 0;
2010 case Intrinsic::memmove_i32:
2011 case Intrinsic::memmove_i64:
2012 visitMemIntrinsic(I, ISD::MEMMOVE);
2013 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002014
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002015 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002016 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002017 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002018 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002019 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002020
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002021 Ops[0] = getRoot();
2022 Ops[1] = getValue(SPI.getLineValue());
2023 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002024
Jim Laskeyc56315c2007-01-26 21:22:28 +00002025 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002026 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002027 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2028
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002029 Ops[3] = DAG.getString(CompileUnit->getFileName());
2030 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002031
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002032 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002033 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002034
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002035 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002036 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002037 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002038 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002039 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002040 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2041 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002042 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002043 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002044 }
2045
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002046 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002047 }
2048 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002049 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002050 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002051 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2052 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002053 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002054 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002055 }
2056
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002057 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002058 }
2059 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002060 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002061 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002062 if (MMI && FSI.getSubprogram() &&
2063 MMI->Verify(FSI.getSubprogram())) {
2064 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002065 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002066 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002067 }
2068
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002069 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002070 }
2071 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002072 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002073 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002074 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002075 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002076 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002077 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002078 }
2079
2080 return 0;
2081 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002082
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002083 case Intrinsic::eh_exception: {
2084 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2085
Jim Laskey504e9942007-02-22 15:38:06 +00002086 if (MMI) {
2087 // Add a label to mark the beginning of the landing pad. Deletion of the
2088 // landing pad can thus be detected via the MachineModuleInfo.
2089 unsigned LabelID = MMI->addLandingPad(CurMBB);
2090 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2091 DAG.getConstant(LabelID, MVT::i32)));
2092
2093 // Mark exception register as live in.
2094 unsigned Reg = TLI.getExceptionAddressRegister();
2095 if (Reg) CurMBB->addLiveIn(Reg);
2096
2097 // Insert the EXCEPTIONADDR instruction.
2098 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2099 SDOperand Ops[1];
2100 Ops[0] = DAG.getRoot();
2101 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2102 setValue(&I, Op);
2103 DAG.setRoot(Op.getValue(1));
2104 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002105 return 0;
2106 }
2107
2108 case Intrinsic::eh_handlers: {
2109 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2110
Jim Laskey504e9942007-02-22 15:38:06 +00002111 if (MMI) {
2112 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002113 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2114 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2115 isa<Function>(CE->getOperand(0)) &&
2116 "Personality should be a function");
2117 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002118
Jim Laskey504e9942007-02-22 15:38:06 +00002119 // Gather all the type infos for this landing pad and pass them along to
2120 // MachineModuleInfo.
2121 std::vector<GlobalVariable *> TyInfo;
2122 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskey44c37e72007-02-22 16:10:05 +00002123 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2124 if (CE && CE->getOpcode() == Instruction::BitCast &&
2125 isa<GlobalVariable>(CE->getOperand(0))) {
2126 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2127 } else {
2128 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2129 assert(CI && CI->getZExtValue() == 0 &&
2130 "TypeInfo must be a global variable typeinfo or NULL");
2131 TyInfo.push_back(NULL);
Jim Laskey504e9942007-02-22 15:38:06 +00002132 }
Jim Laskey504e9942007-02-22 15:38:06 +00002133 }
2134 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2135
2136 // Mark exception selector register as live in.
2137 unsigned Reg = TLI.getExceptionSelectorRegister();
2138 if (Reg) CurMBB->addLiveIn(Reg);
2139
2140 // Insert the EHSELECTION instruction.
2141 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2142 SDOperand Ops[2];
2143 Ops[0] = getValue(I.getOperand(1));
2144 Ops[1] = getRoot();
2145 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2146 setValue(&I, Op);
2147 DAG.setRoot(Op.getValue(1));
2148 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002149
2150 return 0;
2151 }
2152
2153 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002154 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002155
Jim Laskey504e9942007-02-22 15:38:06 +00002156 if (MMI) {
2157 // Find the type id for the given typeinfo.
2158 GlobalVariable *GV = NULL;
Jim Laskey44c37e72007-02-22 16:10:05 +00002159 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2160 if (CE && CE->getOpcode() == Instruction::BitCast &&
2161 isa<GlobalVariable>(CE->getOperand(0))) {
2162 GV = cast<GlobalVariable>(CE->getOperand(0));
2163 } else {
2164 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2165 assert(CI && CI->getZExtValue() == 0 &&
2166 "TypeInfo must be a global variable typeinfo or NULL");
2167 GV = NULL;
Jim Laskey504e9942007-02-22 15:38:06 +00002168 }
2169
2170 unsigned TypeID = MMI->getTypeIDFor(GV);
2171 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2172 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002173
2174 return 0;
2175 }
2176
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002177 case Intrinsic::sqrt_f32:
2178 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002179 setValue(&I, DAG.getNode(ISD::FSQRT,
2180 getValue(I.getOperand(1)).getValueType(),
2181 getValue(I.getOperand(1))));
2182 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002183 case Intrinsic::powi_f32:
2184 case Intrinsic::powi_f64:
2185 setValue(&I, DAG.getNode(ISD::FPOWI,
2186 getValue(I.getOperand(1)).getValueType(),
2187 getValue(I.getOperand(1)),
2188 getValue(I.getOperand(2))));
2189 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002190 case Intrinsic::pcmarker: {
2191 SDOperand Tmp = getValue(I.getOperand(1));
2192 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2193 return 0;
2194 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002195 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002196 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002197 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2198 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2199 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002200 setValue(&I, Tmp);
2201 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002202 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002203 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00002204 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002205 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002206 case Intrinsic::bswap_i64:
2207 setValue(&I, DAG.getNode(ISD::BSWAP,
2208 getValue(I.getOperand(1)).getValueType(),
2209 getValue(I.getOperand(1))));
2210 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002211 case Intrinsic::cttz_i8:
2212 case Intrinsic::cttz_i16:
2213 case Intrinsic::cttz_i32:
2214 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002215 setValue(&I, DAG.getNode(ISD::CTTZ,
2216 getValue(I.getOperand(1)).getValueType(),
2217 getValue(I.getOperand(1))));
2218 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002219 case Intrinsic::ctlz_i8:
2220 case Intrinsic::ctlz_i16:
2221 case Intrinsic::ctlz_i32:
2222 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002223 setValue(&I, DAG.getNode(ISD::CTLZ,
2224 getValue(I.getOperand(1)).getValueType(),
2225 getValue(I.getOperand(1))));
2226 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002227 case Intrinsic::ctpop_i8:
2228 case Intrinsic::ctpop_i16:
2229 case Intrinsic::ctpop_i32:
2230 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002231 setValue(&I, DAG.getNode(ISD::CTPOP,
2232 getValue(I.getOperand(1)).getValueType(),
2233 getValue(I.getOperand(1))));
2234 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00002235 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002236 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002237 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2238 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002239 setValue(&I, Tmp);
2240 DAG.setRoot(Tmp.getValue(1));
2241 return 0;
2242 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002243 case Intrinsic::stackrestore: {
2244 SDOperand Tmp = getValue(I.getOperand(1));
2245 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002246 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002247 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002248 case Intrinsic::prefetch:
2249 // FIXME: Currently discarding prefetches.
2250 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002251 }
2252}
2253
2254
Jim Laskey31fef782007-02-23 21:45:01 +00002255void SelectionDAGLowering::LowerCallTo(Instruction &I,
2256 const Type *CalledValueTy,
2257 unsigned CallingConv,
2258 bool IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002259 SDOperand Callee, unsigned OpIdx) {
Jim Laskey31fef782007-02-23 21:45:01 +00002260 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002261 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2262
2263 TargetLowering::ArgListTy Args;
2264 TargetLowering::ArgListEntry Entry;
2265 Args.reserve(I.getNumOperands());
2266 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2267 Value *Arg = I.getOperand(i);
2268 SDOperand ArgNode = getValue(Arg);
2269 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2270 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2271 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2272 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2273 Args.push_back(Entry);
2274 }
2275
2276 std::pair<SDOperand,SDOperand> Result =
2277 TLI.LowerCallTo(getRoot(), I.getType(),
2278 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
Jim Laskey31fef782007-02-23 21:45:01 +00002279 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002280 Callee, Args, DAG);
2281 if (I.getType() != Type::VoidTy)
2282 setValue(&I, Result.first);
2283 DAG.setRoot(Result.second);
2284}
2285
2286
Chris Lattner7a60d912005-01-07 07:47:53 +00002287void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002288 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002289 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002290 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002291 if (unsigned IID = F->getIntrinsicID()) {
2292 RenameFn = visitIntrinsicCall(I, IID);
2293 if (!RenameFn)
2294 return;
2295 } else { // Not an LLVM intrinsic.
2296 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002297 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2298 if (I.getNumOperands() == 3 && // Basic sanity checks.
2299 I.getOperand(1)->getType()->isFloatingPoint() &&
2300 I.getType() == I.getOperand(1)->getType() &&
2301 I.getType() == I.getOperand(2)->getType()) {
2302 SDOperand LHS = getValue(I.getOperand(1));
2303 SDOperand RHS = getValue(I.getOperand(2));
2304 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2305 LHS, RHS));
2306 return;
2307 }
2308 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002309 if (I.getNumOperands() == 2 && // Basic sanity checks.
2310 I.getOperand(1)->getType()->isFloatingPoint() &&
2311 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002312 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002313 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2314 return;
2315 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002316 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002317 if (I.getNumOperands() == 2 && // Basic sanity checks.
2318 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002319 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002320 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002321 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2322 return;
2323 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002324 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002325 if (I.getNumOperands() == 2 && // Basic sanity checks.
2326 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002327 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002328 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002329 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2330 return;
2331 }
2332 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002333 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002334 } else if (isa<InlineAsm>(I.getOperand(0))) {
2335 visitInlineAsm(I);
2336 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002337 }
Misha Brukman835702a2005-04-21 22:36:52 +00002338
Chris Lattner18d2b342005-01-08 22:48:57 +00002339 SDOperand Callee;
2340 if (!RenameFn)
2341 Callee = getValue(I.getOperand(0));
2342 else
2343 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey504e9942007-02-22 15:38:06 +00002344
Jim Laskey31fef782007-02-23 21:45:01 +00002345 LowerCallTo(I, I.getCalledValue()->getType(),
2346 I.getCallingConv(),
2347 I.isTailCall(),
2348 Callee,
2349 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002350}
2351
Jim Laskey504e9942007-02-22 15:38:06 +00002352
Chris Lattner6f87d182006-02-22 22:37:12 +00002353SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002354 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002355 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2356 Chain = Val.getValue(1);
2357 Flag = Val.getValue(2);
2358
2359 // If the result was expanded, copy from the top part.
2360 if (Regs.size() > 1) {
2361 assert(Regs.size() == 2 &&
2362 "Cannot expand to more than 2 elts yet!");
2363 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002364 Chain = Hi.getValue(1);
2365 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002366 if (DAG.getTargetLoweringInfo().isLittleEndian())
2367 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2368 else
2369 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002370 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002371
Chris Lattner705948d2006-06-08 18:22:48 +00002372 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002373 // appropriate type.
2374 if (RegVT == ValueVT)
2375 return Val;
2376
Chris Lattner705948d2006-06-08 18:22:48 +00002377 if (MVT::isInteger(RegVT)) {
2378 if (ValueVT < RegVT)
2379 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2380 else
2381 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2382 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00002383 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002384 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002385}
2386
Chris Lattner571d9642006-02-23 19:21:04 +00002387/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2388/// specified value into the registers specified by this object. This uses
2389/// Chain/Flag as the input and updates them for the output Chain/Flag.
2390void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002391 SDOperand &Chain, SDOperand &Flag,
2392 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002393 if (Regs.size() == 1) {
2394 // If there is a single register and the types differ, this must be
2395 // a promotion.
2396 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002397 if (MVT::isInteger(RegVT)) {
2398 if (RegVT < ValueVT)
2399 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2400 else
2401 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2402 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002403 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2404 }
2405 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2406 Flag = Chain.getValue(1);
2407 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002408 std::vector<unsigned> R(Regs);
2409 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2410 std::reverse(R.begin(), R.end());
2411
2412 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002413 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002414 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002415 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002416 Flag = Chain.getValue(1);
2417 }
2418 }
2419}
Chris Lattner6f87d182006-02-22 22:37:12 +00002420
Chris Lattner571d9642006-02-23 19:21:04 +00002421/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2422/// operand list. This adds the code marker and includes the number of
2423/// values added into it.
2424void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002425 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002426 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2427 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2428 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2429}
Chris Lattner6f87d182006-02-22 22:37:12 +00002430
2431/// isAllocatableRegister - If the specified register is safe to allocate,
2432/// i.e. it isn't a stack pointer or some other special register, return the
2433/// register class for the register. Otherwise, return null.
2434static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002435isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2436 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002437 MVT::ValueType FoundVT = MVT::Other;
2438 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002439 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2440 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002441 MVT::ValueType ThisVT = MVT::Other;
2442
Chris Lattnerb1124f32006-02-22 23:09:03 +00002443 const TargetRegisterClass *RC = *RCI;
2444 // If none of the the value types for this register class are valid, we
2445 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002446 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2447 I != E; ++I) {
2448 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002449 // If we have already found this register in a different register class,
2450 // choose the one with the largest VT specified. For example, on
2451 // PowerPC, we favor f64 register classes over f32.
2452 if (FoundVT == MVT::Other ||
2453 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2454 ThisVT = *I;
2455 break;
2456 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002457 }
2458 }
2459
Chris Lattnerbec582f2006-04-02 00:24:45 +00002460 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002461
Chris Lattner6f87d182006-02-22 22:37:12 +00002462 // NOTE: This isn't ideal. In particular, this might allocate the
2463 // frame pointer in functions that need it (due to them not being taken
2464 // out of allocation, because a variable sized allocation hasn't been seen
2465 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002466 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2467 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002468 if (*I == Reg) {
2469 // We found a matching register class. Keep looking at others in case
2470 // we find one with larger registers that this physreg is also in.
2471 FoundRC = RC;
2472 FoundVT = ThisVT;
2473 break;
2474 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002475 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002476 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002477}
2478
2479RegsForValue SelectionDAGLowering::
2480GetRegistersForValue(const std::string &ConstrCode,
2481 MVT::ValueType VT, bool isOutReg, bool isInReg,
2482 std::set<unsigned> &OutputRegs,
2483 std::set<unsigned> &InputRegs) {
2484 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2485 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2486 std::vector<unsigned> Regs;
2487
2488 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2489 MVT::ValueType RegVT;
2490 MVT::ValueType ValueVT = VT;
2491
Chris Lattner55402d42006-11-02 01:41:49 +00002492 // If this is a constraint for a specific physical register, like {r17},
2493 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002494 if (PhysReg.first) {
2495 if (VT == MVT::Other)
2496 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002497
2498 // Get the actual register value type. This is important, because the user
2499 // may have asked for (e.g.) the AX register in i32 type. We need to
2500 // remember that AX is actually i16 to get the right extension.
2501 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002502
2503 // This is a explicit reference to a physical register.
2504 Regs.push_back(PhysReg.first);
2505
2506 // If this is an expanded reference, add the rest of the regs to Regs.
2507 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002508 TargetRegisterClass::iterator I = PhysReg.second->begin();
2509 TargetRegisterClass::iterator E = PhysReg.second->end();
2510 for (; *I != PhysReg.first; ++I)
2511 assert(I != E && "Didn't find reg!");
2512
2513 // Already added the first reg.
2514 --NumRegs; ++I;
2515 for (; NumRegs; --NumRegs, ++I) {
2516 assert(I != E && "Ran out of registers to allocate!");
2517 Regs.push_back(*I);
2518 }
2519 }
2520 return RegsForValue(Regs, RegVT, ValueVT);
2521 }
2522
Chris Lattner55402d42006-11-02 01:41:49 +00002523 // Otherwise, if this was a reference to an LLVM register class, create vregs
2524 // for this reference.
2525 std::vector<unsigned> RegClassRegs;
2526 if (PhysReg.second) {
2527 // If this is an early clobber or tied register, our regalloc doesn't know
2528 // how to maintain the constraint. If it isn't, go ahead and create vreg
2529 // and let the regalloc do the right thing.
2530 if (!isOutReg || !isInReg) {
2531 if (VT == MVT::Other)
2532 ValueVT = *PhysReg.second->vt_begin();
2533 RegVT = *PhysReg.second->vt_begin();
2534
2535 // Create the appropriate number of virtual registers.
2536 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2537 for (; NumRegs; --NumRegs)
2538 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2539
2540 return RegsForValue(Regs, RegVT, ValueVT);
2541 }
2542
2543 // Otherwise, we can't allocate it. Let the code below figure out how to
2544 // maintain these constraints.
2545 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2546
2547 } else {
2548 // This is a reference to a register class that doesn't directly correspond
2549 // to an LLVM register class. Allocate NumRegs consecutive, available,
2550 // registers from the class.
2551 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2552 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002553
2554 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2555 MachineFunction &MF = *CurMBB->getParent();
2556 unsigned NumAllocated = 0;
2557 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2558 unsigned Reg = RegClassRegs[i];
2559 // See if this register is available.
2560 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2561 (isInReg && InputRegs.count(Reg))) { // Already used.
2562 // Make sure we find consecutive registers.
2563 NumAllocated = 0;
2564 continue;
2565 }
2566
2567 // Check to see if this register is allocatable (i.e. don't give out the
2568 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002569 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002570 if (!RC) {
2571 // Make sure we find consecutive registers.
2572 NumAllocated = 0;
2573 continue;
2574 }
2575
2576 // Okay, this register is good, we can use it.
2577 ++NumAllocated;
2578
2579 // If we allocated enough consecutive
2580 if (NumAllocated == NumRegs) {
2581 unsigned RegStart = (i-NumAllocated)+1;
2582 unsigned RegEnd = i+1;
2583 // Mark all of the allocated registers used.
2584 for (unsigned i = RegStart; i != RegEnd; ++i) {
2585 unsigned Reg = RegClassRegs[i];
2586 Regs.push_back(Reg);
2587 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2588 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2589 }
2590
2591 return RegsForValue(Regs, *RC->vt_begin(), VT);
2592 }
2593 }
2594
2595 // Otherwise, we couldn't allocate enough registers for this.
2596 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002597}
2598
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002599/// getConstraintGenerality - Return an integer indicating how general CT is.
2600static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2601 switch (CT) {
2602 default: assert(0 && "Unknown constraint type!");
2603 case TargetLowering::C_Other:
2604 case TargetLowering::C_Unknown:
2605 return 0;
2606 case TargetLowering::C_Register:
2607 return 1;
2608 case TargetLowering::C_RegisterClass:
2609 return 2;
2610 case TargetLowering::C_Memory:
2611 return 3;
2612 }
2613}
2614
2615static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2616 const TargetLowering &TLI) {
2617 assert(!C.empty() && "Must have at least one constraint");
2618 if (C.size() == 1) return C[0];
2619
2620 std::string *Current = &C[0];
2621 // If we have multiple constraints, try to pick the most general one ahead
2622 // of time. This isn't a wonderful solution, but handles common cases.
2623 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0][0]);
2624 for (unsigned j = 1, e = C.size(); j != e; ++j) {
2625 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j][0]);
2626 if (getConstraintGenerality(ThisFlavor) >
2627 getConstraintGenerality(Flavor)) {
2628 // This constraint letter is more general than the previous one,
2629 // use it.
2630 Flavor = ThisFlavor;
2631 Current = &C[j];
2632 }
2633 }
2634 return *Current;
2635}
2636
Chris Lattner6f87d182006-02-22 22:37:12 +00002637
Chris Lattner476e67b2006-01-26 22:24:51 +00002638/// visitInlineAsm - Handle a call to an InlineAsm object.
2639///
2640void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2641 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2642
2643 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2644 MVT::Other);
2645
Chris Lattner3a5ed552006-02-01 01:28:23 +00002646 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002647 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002648
2649 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2650 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2651 /// if it is a def of that register.
2652 std::vector<SDOperand> AsmNodeOperands;
2653 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2654 AsmNodeOperands.push_back(AsmStr);
2655
2656 SDOperand Chain = getRoot();
2657 SDOperand Flag;
2658
Chris Lattner1558fc62006-02-01 18:59:47 +00002659 // We fully assign registers here at isel time. This is not optimal, but
2660 // should work. For register classes that correspond to LLVM classes, we
2661 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2662 // over the constraints, collecting fixed registers that we know we can't use.
2663 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002664 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002665 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002666 std::string ConstraintCode =
2667 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7f5880b2006-02-02 00:25:23 +00002668
Chris Lattner7ad77df2006-02-22 00:56:39 +00002669 MVT::ValueType OpVT;
2670
2671 // Compute the value type for each operand and add it to ConstraintVTs.
2672 switch (Constraints[i].Type) {
2673 case InlineAsm::isOutput:
2674 if (!Constraints[i].isIndirectOutput) {
2675 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2676 OpVT = TLI.getValueType(I.getType());
2677 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002678 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002679 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2680 OpNum++; // Consumes a call operand.
2681 }
2682 break;
2683 case InlineAsm::isInput:
2684 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2685 OpNum++; // Consumes a call operand.
2686 break;
2687 case InlineAsm::isClobber:
2688 OpVT = MVT::Other;
2689 break;
2690 }
2691
2692 ConstraintVTs.push_back(OpVT);
2693
Chris Lattner6f87d182006-02-22 22:37:12 +00002694 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2695 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002696
Chris Lattner6f87d182006-02-22 22:37:12 +00002697 // Build a list of regs that this operand uses. This always has a single
2698 // element for promoted/expanded operands.
2699 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2700 false, false,
2701 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002702
2703 switch (Constraints[i].Type) {
2704 case InlineAsm::isOutput:
2705 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002706 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002707 // If this is an early-clobber output, it cannot be assigned to the same
2708 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002709 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002710 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002711 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002712 case InlineAsm::isInput:
2713 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002714 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002715 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002716 case InlineAsm::isClobber:
2717 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002718 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2719 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002720 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002721 }
2722 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002723
Chris Lattner5c79f982006-02-21 23:12:12 +00002724 // Loop over all of the inputs, copying the operand values into the
2725 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002726 RegsForValue RetValRegs;
2727 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002728 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002729
Chris Lattner2e56e892006-01-31 02:03:41 +00002730 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattnerd27f95e2007-01-29 23:45:14 +00002731 std::string ConstraintCode =
2732 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002733
Chris Lattner3a5ed552006-02-01 01:28:23 +00002734 switch (Constraints[i].Type) {
2735 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002736 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2737 if (ConstraintCode.size() == 1) // not a physreg name.
2738 CTy = TLI.getConstraintType(ConstraintCode[0]);
2739
2740 if (CTy == TargetLowering::C_Memory) {
2741 // Memory output.
2742 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2743
2744 // Check that the operand (the address to store to) isn't a float.
2745 if (!MVT::isInteger(InOperandVal.getValueType()))
2746 assert(0 && "MATCH FAIL!");
2747
2748 if (!Constraints[i].isIndirectOutput)
2749 assert(0 && "MATCH FAIL!");
2750
2751 OpNum++; // Consumes a call operand.
2752
2753 // Extend/truncate to the right pointer type if needed.
2754 MVT::ValueType PtrType = TLI.getPointerTy();
2755 if (InOperandVal.getValueType() < PtrType)
2756 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2757 else if (InOperandVal.getValueType() > PtrType)
2758 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2759
2760 // Add information to the INLINEASM node to know about this output.
2761 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2762 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2763 AsmNodeOperands.push_back(InOperandVal);
2764 break;
2765 }
2766
2767 // Otherwise, this is a register output.
2768 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2769
Chris Lattner6f87d182006-02-22 22:37:12 +00002770 // If this is an early-clobber output, or if there is an input
2771 // constraint that matches this, we need to reserve the input register
2772 // so no other inputs allocate to it.
2773 bool UsesInputRegister = false;
2774 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2775 UsesInputRegister = true;
2776
2777 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002778 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002779 RegsForValue Regs =
2780 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2781 true, UsesInputRegister,
2782 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002783 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002784 cerr << "Couldn't allocate output reg for contraint '"
2785 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00002786 exit(1);
2787 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002788
Chris Lattner3a5ed552006-02-01 01:28:23 +00002789 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002790 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002791 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002792 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002793 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002794 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002795 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2796 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002797 OpNum++; // Consumes a call operand.
2798 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002799
2800 // Add information to the INLINEASM node to know that this register is
2801 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002802 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002803 break;
2804 }
2805 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002806 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002807 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002808
Chris Lattner7f5880b2006-02-02 00:25:23 +00002809 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2810 // If this is required to match an output register we have already set,
2811 // just use its register.
2812 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002813
Chris Lattner571d9642006-02-23 19:21:04 +00002814 // Scan until we find the definition we already emitted of this operand.
2815 // When we find it, create a RegsForValue operand.
2816 unsigned CurOp = 2; // The first operand.
2817 for (; OperandNo; --OperandNo) {
2818 // Advance to the next operand.
2819 unsigned NumOps =
2820 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002821 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2822 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002823 "Skipped past definitions?");
2824 CurOp += (NumOps>>3)+1;
2825 }
2826
2827 unsigned NumOps =
2828 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00002829 if ((NumOps & 7) == 2 /*REGDEF*/) {
2830 // Add NumOps>>3 registers to MatchedRegs.
2831 RegsForValue MatchedRegs;
2832 MatchedRegs.ValueVT = InOperandVal.getValueType();
2833 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2834 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2835 unsigned Reg =
2836 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2837 MatchedRegs.Regs.push_back(Reg);
2838 }
Chris Lattner571d9642006-02-23 19:21:04 +00002839
Chris Lattnere3eeb242007-02-01 01:21:12 +00002840 // Use the produced MatchedRegs object to
2841 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2842 TLI.getPointerTy());
2843 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2844 break;
2845 } else {
2846 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2847 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00002848 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00002849 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002850
2851 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2852 if (ConstraintCode.size() == 1) // not a physreg name.
2853 CTy = TLI.getConstraintType(ConstraintCode[0]);
2854
2855 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00002856 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2857 ConstraintCode[0], DAG);
2858 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002859 cerr << "Invalid operand for inline asm constraint '"
2860 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00002861 exit(1);
2862 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002863
2864 // Add information to the INLINEASM node to know about this input.
2865 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2866 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2867 AsmNodeOperands.push_back(InOperandVal);
2868 break;
2869 } else if (CTy == TargetLowering::C_Memory) {
2870 // Memory input.
2871
2872 // Check that the operand isn't a float.
2873 if (!MVT::isInteger(InOperandVal.getValueType()))
2874 assert(0 && "MATCH FAIL!");
2875
2876 // Extend/truncate to the right pointer type if needed.
2877 MVT::ValueType PtrType = TLI.getPointerTy();
2878 if (InOperandVal.getValueType() < PtrType)
2879 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2880 else if (InOperandVal.getValueType() > PtrType)
2881 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2882
2883 // Add information to the INLINEASM node to know about this input.
2884 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2885 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2886 AsmNodeOperands.push_back(InOperandVal);
2887 break;
2888 }
2889
2890 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2891
2892 // Copy the input into the appropriate registers.
2893 RegsForValue InRegs =
2894 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2895 false, true, OutputRegs, InputRegs);
2896 // FIXME: should be match fail.
2897 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2898
Evan Chengef9e07d2006-06-15 08:11:54 +00002899 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002900
2901 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002902 break;
2903 }
Chris Lattner571d9642006-02-23 19:21:04 +00002904 case InlineAsm::isClobber: {
2905 RegsForValue ClobberedRegs =
2906 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2907 OutputRegs, InputRegs);
2908 // Add the clobbered value to the operand list, so that the register
2909 // allocator is aware that the physreg got clobbered.
2910 if (!ClobberedRegs.Regs.empty())
2911 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002912 break;
2913 }
Chris Lattner571d9642006-02-23 19:21:04 +00002914 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002915 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002916
2917 // Finish up input operands.
2918 AsmNodeOperands[0] = Chain;
2919 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2920
Chris Lattnerbd887772006-08-14 23:53:35 +00002921 Chain = DAG.getNode(ISD::INLINEASM,
2922 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002923 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002924 Flag = Chain.getValue(1);
2925
Chris Lattner2e56e892006-01-31 02:03:41 +00002926 // If this asm returns a register value, copy the result from that register
2927 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002928 if (!RetValRegs.Regs.empty())
2929 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002930
Chris Lattner2e56e892006-01-31 02:03:41 +00002931 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2932
2933 // Process indirect outputs, first output all of the flagged copies out of
2934 // physregs.
2935 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002936 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002937 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002938 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2939 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002940 }
2941
2942 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002943 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002944 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002945 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002946 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002947 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002948 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002949 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2950 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002951 DAG.setRoot(Chain);
2952}
2953
2954
Chris Lattner7a60d912005-01-07 07:47:53 +00002955void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2956 SDOperand Src = getValue(I.getOperand(0));
2957
2958 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002959
2960 if (IntPtr < Src.getValueType())
2961 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2962 else if (IntPtr > Src.getValueType())
2963 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002964
2965 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002966 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002967 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2968 Src, getIntPtrConstant(ElementSize));
2969
Reid Spencere63b6512006-12-31 05:55:36 +00002970 TargetLowering::ArgListTy Args;
2971 TargetLowering::ArgListEntry Entry;
2972 Entry.Node = Src;
2973 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2974 Entry.isSigned = false;
Anton Korobeynikov037c8672007-01-28 13:31:35 +00002975 Entry.isInReg = false;
2976 Entry.isSRet = false;
Reid Spencere63b6512006-12-31 05:55:36 +00002977 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00002978
2979 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00002980 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002981 DAG.getExternalSymbol("malloc", IntPtr),
2982 Args, DAG);
2983 setValue(&I, Result.first); // Pointers always fit in registers
2984 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002985}
2986
2987void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00002988 TargetLowering::ArgListTy Args;
2989 TargetLowering::ArgListEntry Entry;
2990 Entry.Node = getValue(I.getOperand(0));
2991 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2992 Entry.isSigned = false;
Anton Korobeynikov037c8672007-01-28 13:31:35 +00002993 Entry.isInReg = false;
2994 Entry.isSRet = false;
Reid Spencere63b6512006-12-31 05:55:36 +00002995 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00002996 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002997 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00002998 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002999 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3000 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003001}
3002
Chris Lattner13d7c252005-08-26 20:54:47 +00003003// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3004// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3005// instructions are special in various ways, which require special support to
3006// insert. The specified MachineInstr is created but not inserted into any
3007// basic blocks, and the scheduler passes ownership of it to this method.
3008MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3009 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003010 cerr << "If a target marks an instruction with "
3011 << "'usesCustomDAGSchedInserter', it must implement "
3012 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003013 abort();
3014 return 0;
3015}
3016
Chris Lattner58cfd792005-01-09 00:00:49 +00003017void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003018 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3019 getValue(I.getOperand(1)),
3020 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003021}
3022
3023void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003024 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3025 getValue(I.getOperand(0)),
3026 DAG.getSrcValue(I.getOperand(0)));
3027 setValue(&I, V);
3028 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003029}
3030
3031void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003032 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3033 getValue(I.getOperand(1)),
3034 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003035}
3036
3037void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003038 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3039 getValue(I.getOperand(1)),
3040 getValue(I.getOperand(2)),
3041 DAG.getSrcValue(I.getOperand(1)),
3042 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003043}
3044
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003045/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3046/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3047static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3048 unsigned &i, SelectionDAG &DAG,
3049 TargetLowering &TLI) {
3050 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3051 return SDOperand(Arg, i++);
3052
3053 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3054 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3055 if (NumVals == 1) {
3056 return DAG.getNode(ISD::BIT_CONVERT, VT,
3057 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3058 } else if (NumVals == 2) {
3059 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3060 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3061 if (!TLI.isLittleEndian())
3062 std::swap(Lo, Hi);
3063 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3064 } else {
3065 // Value scalarized into many values. Unimp for now.
3066 assert(0 && "Cannot expand i64 -> i16 yet!");
3067 }
3068 return SDOperand();
3069}
3070
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003071/// TargetLowering::LowerArguments - This is the default LowerArguments
3072/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003073/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3074/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003075std::vector<SDOperand>
3076TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003077 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003078 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3079 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003080 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003081 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3082 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3083
3084 // Add one result value for each formal argument.
3085 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003086 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003087 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3088 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003089 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003090 bool isInReg = FTy->paramHasAttr(j, FunctionType::InRegAttribute);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003091 bool isSRet = FTy->paramHasAttr(j, FunctionType::StructRetAttribute);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003092 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003093 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003094 // Flags[31:27] -> OriginalAlignment
3095 // Flags[2] -> isSRet
3096 // Flags[1] -> isInReg
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003097 unsigned Flags = (isInReg << 1) | (isSRet << 2) | (OriginalAlignment << 27);
3098
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003099 switch (getTypeAction(VT)) {
3100 default: assert(0 && "Unknown type action!");
3101 case Legal:
3102 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003103 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003104 break;
3105 case Promote:
3106 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003107 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003108 break;
3109 case Expand:
3110 if (VT != MVT::Vector) {
3111 // If this is a large integer, it needs to be broken up into small
3112 // integers. Figure out what the destination type is and how many small
3113 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003114 MVT::ValueType NVT = getTypeToExpandTo(VT);
3115 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003116 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003117 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003118 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003119 if (i == 1) Flags = (Flags & 0x07ffffff) | (1 << 27);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003120 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3121 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003122 } else {
3123 // Otherwise, this is a vector type. We only support legal vectors
3124 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003125 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3126 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003127
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003128 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003129 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003130 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3131 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3132 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003133 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003134 } else {
3135 assert(0 && "Don't support illegal by-val vector arguments yet!");
3136 }
3137 }
3138 break;
3139 }
3140 }
Evan Cheng9618df12006-04-25 23:03:35 +00003141
Chris Lattner3d826992006-05-16 06:45:34 +00003142 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003143
3144 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003145 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3146 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003147 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003148
3149 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003150
3151 // Set up the return result vector.
3152 Ops.clear();
3153 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003154 unsigned Idx = 1;
3155 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3156 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003157 MVT::ValueType VT = getValueType(I->getType());
3158
3159 switch (getTypeAction(VT)) {
3160 default: assert(0 && "Unknown type action!");
3161 case Legal:
3162 Ops.push_back(SDOperand(Result, i++));
3163 break;
3164 case Promote: {
3165 SDOperand Op(Result, i++);
3166 if (MVT::isInteger(VT)) {
Chris Lattner96035be2007-01-04 22:22:37 +00003167 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3168 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3169 DAG.getValueType(VT));
3170 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3171 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3172 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003173 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3174 } else {
3175 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3176 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3177 }
3178 Ops.push_back(Op);
3179 break;
3180 }
3181 case Expand:
3182 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003183 // If this is a large integer or a floating point node that needs to be
3184 // expanded, it needs to be reassembled from small integers. Figure out
3185 // what the source elt type is and how many small integers it is.
3186 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003187 } else {
3188 // Otherwise, this is a vector type. We only support legal vectors
3189 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003190 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003191 unsigned NumElems = PTy->getNumElements();
3192 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003193
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003194 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003195 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003196 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003197 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003198 SDOperand N = SDOperand(Result, i++);
3199 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003200 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3201 DAG.getConstant(NumElems, MVT::i32),
3202 DAG.getValueType(getValueType(EltTy)));
3203 Ops.push_back(N);
3204 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003205 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003206 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003207 }
3208 }
3209 break;
3210 }
3211 }
3212 return Ops;
3213}
3214
Chris Lattneraaa23d92006-05-16 22:53:20 +00003215
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003216/// ExpandScalarCallArgs - Recursively expand call argument node by
3217/// bit_converting it or extract a pair of elements from the larger node.
3218static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003219 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003220 SmallVector<SDOperand, 32> &Ops,
3221 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003222 TargetLowering &TLI,
3223 bool isFirst = true) {
3224
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003225 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003226 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003227 if (!isFirst)
3228 Flags = (Flags & 0x07ffffff) | (1 << 27);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003229 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003230 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003231 return;
3232 }
3233
3234 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3235 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3236 if (NumVals == 1) {
3237 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003238 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003239 } else if (NumVals == 2) {
3240 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3241 DAG.getConstant(0, TLI.getPointerTy()));
3242 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3243 DAG.getConstant(1, TLI.getPointerTy()));
3244 if (!TLI.isLittleEndian())
3245 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003246 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3247 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003248 } else {
3249 // Value scalarized into many values. Unimp for now.
3250 assert(0 && "Cannot expand i64 -> i16 yet!");
3251 }
3252}
3253
Chris Lattneraaa23d92006-05-16 22:53:20 +00003254/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3255/// implementation, which just inserts an ISD::CALL node, which is later custom
3256/// lowered by the target to something concrete. FIXME: When all targets are
3257/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3258std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003259TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3260 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003261 unsigned CallingConv, bool isTailCall,
3262 SDOperand Callee,
3263 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003264 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003265 Ops.push_back(Chain); // Op#0 - Chain
3266 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3267 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3268 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3269 Ops.push_back(Callee);
3270
3271 // Handle all of the outgoing arguments.
3272 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003273 MVT::ValueType VT = getValueType(Args[i].Ty);
3274 SDOperand Op = Args[i].Node;
3275 bool isSigned = Args[i].isSigned;
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003276 bool isInReg = Args[i].isInReg;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003277 bool isSRet = Args[i].isSRet;
3278 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003279 getTargetData()->getABITypeAlignment(Args[i].Ty);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003280 // Flags[31:27] -> OriginalAlignment
3281 // Flags[2] -> isSRet
3282 // Flags[1] -> isInReg
3283 // Flags[0] -> isSigned
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003284 unsigned Flags = (isSRet << 2) | (isInReg << 1) | isSigned |
3285 (OriginalAlignment << 27);
3286
Chris Lattneraaa23d92006-05-16 22:53:20 +00003287 switch (getTypeAction(VT)) {
3288 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003289 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003290 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003291 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003292 break;
3293 case Promote:
3294 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00003295 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003296 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3297 } else {
3298 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3299 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3300 }
3301 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003302 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003303 break;
3304 case Expand:
3305 if (VT != MVT::Vector) {
3306 // If this is a large integer, it needs to be broken down into small
3307 // integers. Figure out what the source elt type is and how many small
3308 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003309 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003310 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003311 // Otherwise, this is a vector type. We only support legal vectors
3312 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003313 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003314 unsigned NumElems = PTy->getNumElements();
3315 const Type *EltTy = PTy->getElementType();
3316
3317 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003318 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003319 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003320 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00003321 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00003322 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3323 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003324 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003325 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003326 assert(0 && "Don't support illegal by-val vector call args yet!");
3327 abort();
3328 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003329 }
3330 break;
3331 }
3332 }
3333
3334 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003335 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003336
3337 if (RetTy != Type::VoidTy) {
3338 MVT::ValueType VT = getValueType(RetTy);
3339 switch (getTypeAction(VT)) {
3340 default: assert(0 && "Unknown type action!");
3341 case Legal:
3342 RetTys.push_back(VT);
3343 break;
3344 case Promote:
3345 RetTys.push_back(getTypeToTransformTo(VT));
3346 break;
3347 case Expand:
3348 if (VT != MVT::Vector) {
3349 // If this is a large integer, it needs to be reassembled from small
3350 // integers. Figure out what the source elt type is and how many small
3351 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003352 MVT::ValueType NVT = getTypeToExpandTo(VT);
3353 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003354 for (unsigned i = 0; i != NumVals; ++i)
3355 RetTys.push_back(NVT);
3356 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003357 // Otherwise, this is a vector type. We only support legal vectors
3358 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003359 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003360 unsigned NumElems = PTy->getNumElements();
3361 const Type *EltTy = PTy->getElementType();
3362
3363 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003364 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003365 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3366 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3367 RetTys.push_back(TVT);
3368 } else {
3369 assert(0 && "Don't support illegal by-val vector call results yet!");
3370 abort();
3371 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003372 }
3373 }
3374 }
3375
3376 RetTys.push_back(MVT::Other); // Always has a chain.
3377
3378 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003379 SDOperand Res = DAG.getNode(ISD::CALL,
3380 DAG.getVTList(&RetTys[0], RetTys.size()),
3381 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003382
3383 // This returns a pair of operands. The first element is the
3384 // return value for the function (if RetTy is not VoidTy). The second
3385 // element is the outgoing token chain.
3386 SDOperand ResVal;
3387 if (RetTys.size() != 1) {
3388 MVT::ValueType VT = getValueType(RetTy);
3389 if (RetTys.size() == 2) {
3390 ResVal = Res;
3391
3392 // If this value was promoted, truncate it down.
3393 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003394 if (VT == MVT::Vector) {
3395 // Insert a VBITCONVERT to convert from the packed result type to the
3396 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003397 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3398 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00003399
3400 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003401 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00003402 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003403 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003404 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3405 // "N x PTyElementVT" MVT::Vector type.
3406 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003407 DAG.getConstant(NumElems, MVT::i32),
3408 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003409 } else {
3410 abort();
3411 }
3412 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00003413 unsigned AssertOp = ISD::AssertSext;
3414 if (!RetTyIsSigned)
3415 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003416 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3417 DAG.getValueType(VT));
3418 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3419 } else {
3420 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003421 if (getTypeAction(VT) == Expand)
3422 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3423 else
3424 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003425 }
3426 }
3427 } else if (RetTys.size() == 3) {
3428 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3429 Res.getValue(0), Res.getValue(1));
3430
3431 } else {
3432 assert(0 && "Case not handled yet!");
3433 }
3434 }
3435
3436 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3437}
3438
Chris Lattner29dcc712005-05-14 05:50:48 +00003439SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003440 assert(0 && "LowerOperation not implemented for this target!");
3441 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003442 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003443}
3444
Nate Begeman595ec732006-01-28 03:14:31 +00003445SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3446 SelectionDAG &DAG) {
3447 assert(0 && "CustomPromoteOperation not implemented for this target!");
3448 abort();
3449 return SDOperand();
3450}
3451
Evan Cheng6781b6e2006-02-15 21:59:04 +00003452/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003453/// operand.
3454static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003455 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003456 MVT::ValueType CurVT = VT;
3457 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3458 uint64_t Val = C->getValue() & 255;
3459 unsigned Shift = 8;
3460 while (CurVT != MVT::i8) {
3461 Val = (Val << Shift) | Val;
3462 Shift <<= 1;
3463 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003464 }
3465 return DAG.getConstant(Val, VT);
3466 } else {
3467 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3468 unsigned Shift = 8;
3469 while (CurVT != MVT::i8) {
3470 Value =
3471 DAG.getNode(ISD::OR, VT,
3472 DAG.getNode(ISD::SHL, VT, Value,
3473 DAG.getConstant(Shift, MVT::i8)), Value);
3474 Shift <<= 1;
3475 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003476 }
3477
3478 return Value;
3479 }
3480}
3481
Evan Cheng6781b6e2006-02-15 21:59:04 +00003482/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3483/// used when a memcpy is turned into a memset when the source is a constant
3484/// string ptr.
3485static SDOperand getMemsetStringVal(MVT::ValueType VT,
3486 SelectionDAG &DAG, TargetLowering &TLI,
3487 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003488 uint64_t Val = 0;
3489 unsigned MSB = getSizeInBits(VT) / 8;
3490 if (TLI.isLittleEndian())
3491 Offset = Offset + MSB - 1;
3492 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00003493 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00003494 Offset += TLI.isLittleEndian() ? -1 : 1;
3495 }
3496 return DAG.getConstant(Val, VT);
3497}
3498
Evan Cheng81fcea82006-02-14 08:22:34 +00003499/// getMemBasePlusOffset - Returns base and offset node for the
3500static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3501 SelectionDAG &DAG, TargetLowering &TLI) {
3502 MVT::ValueType VT = Base.getValueType();
3503 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3504}
3505
Evan Chengdb2a7a72006-02-14 20:12:38 +00003506/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003507/// to replace the memset / memcpy is below the threshold. It also returns the
3508/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003509static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3510 unsigned Limit, uint64_t Size,
3511 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003512 MVT::ValueType VT;
3513
3514 if (TLI.allowsUnalignedMemoryAccesses()) {
3515 VT = MVT::i64;
3516 } else {
3517 switch (Align & 7) {
3518 case 0:
3519 VT = MVT::i64;
3520 break;
3521 case 4:
3522 VT = MVT::i32;
3523 break;
3524 case 2:
3525 VT = MVT::i16;
3526 break;
3527 default:
3528 VT = MVT::i8;
3529 break;
3530 }
3531 }
3532
Evan Chengd5026102006-02-14 09:11:59 +00003533 MVT::ValueType LVT = MVT::i64;
3534 while (!TLI.isTypeLegal(LVT))
3535 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3536 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003537
Evan Chengd5026102006-02-14 09:11:59 +00003538 if (VT > LVT)
3539 VT = LVT;
3540
Evan Cheng04514992006-02-14 23:05:54 +00003541 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003542 while (Size != 0) {
3543 unsigned VTSize = getSizeInBits(VT) / 8;
3544 while (VTSize > Size) {
3545 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003546 VTSize >>= 1;
3547 }
Evan Chengd5026102006-02-14 09:11:59 +00003548 assert(MVT::isInteger(VT));
3549
3550 if (++NumMemOps > Limit)
3551 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003552 MemOps.push_back(VT);
3553 Size -= VTSize;
3554 }
Evan Chengd5026102006-02-14 09:11:59 +00003555
3556 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003557}
3558
Chris Lattner875def92005-01-11 05:56:49 +00003559void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003560 SDOperand Op1 = getValue(I.getOperand(1));
3561 SDOperand Op2 = getValue(I.getOperand(2));
3562 SDOperand Op3 = getValue(I.getOperand(3));
3563 SDOperand Op4 = getValue(I.getOperand(4));
3564 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3565 if (Align == 0) Align = 1;
3566
3567 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3568 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003569
3570 // Expand memset / memcpy to a series of load / store ops
3571 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003572 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003573 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003574 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003575 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003576 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3577 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003578 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003579 unsigned Offset = 0;
3580 for (unsigned i = 0; i < NumMemOps; i++) {
3581 MVT::ValueType VT = MemOps[i];
3582 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003583 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003584 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003585 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003586 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003587 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003588 Offset += VTSize;
3589 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003590 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003591 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003592 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003593 case ISD::MEMCPY: {
3594 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3595 Size->getValue(), Align, TLI)) {
3596 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003597 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003598 GlobalAddressSDNode *G = NULL;
3599 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003600 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003601
3602 if (Op2.getOpcode() == ISD::GlobalAddress)
3603 G = cast<GlobalAddressSDNode>(Op2);
3604 else if (Op2.getOpcode() == ISD::ADD &&
3605 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3606 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3607 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003608 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003609 }
3610 if (G) {
3611 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00003612 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00003613 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003614 if (!Str.empty()) {
3615 CopyFromStr = true;
3616 SrcOff += SrcDelta;
3617 }
3618 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003619 }
3620
Evan Chenge2038bd2006-02-15 01:54:51 +00003621 for (unsigned i = 0; i < NumMemOps; i++) {
3622 MVT::ValueType VT = MemOps[i];
3623 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003624 SDOperand Value, Chain, Store;
3625
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003626 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003627 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3628 Chain = getRoot();
3629 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003630 DAG.getStore(Chain, Value,
3631 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003632 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003633 } else {
3634 Value = DAG.getLoad(VT, getRoot(),
3635 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003636 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003637 Chain = Value.getValue(1);
3638 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003639 DAG.getStore(Chain, Value,
3640 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003641 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003642 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003643 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003644 SrcOff += VTSize;
3645 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003646 }
3647 }
3648 break;
3649 }
3650 }
3651
3652 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003653 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3654 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003655 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003656 }
3657 }
3658
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003659 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003660}
3661
Chris Lattner875def92005-01-11 05:56:49 +00003662//===----------------------------------------------------------------------===//
3663// SelectionDAGISel code
3664//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003665
3666unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3667 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3668}
3669
Chris Lattnerc9950c12005-08-17 06:37:43 +00003670void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003671 // FIXME: we only modify the CFG to split critical edges. This
3672 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003673 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003674}
Chris Lattner7a60d912005-01-07 07:47:53 +00003675
Chris Lattner35397782005-12-05 07:10:48 +00003676
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003677/// OptimizeNoopCopyExpression - We have determined that the specified cast
3678/// instruction is a noop copy (e.g. it's casting from one pointer type to
3679/// another, int->uint, or int->sbyte on PPC.
3680///
3681/// Return true if any changes are made.
3682static bool OptimizeNoopCopyExpression(CastInst *CI) {
3683 BasicBlock *DefBB = CI->getParent();
3684
3685 /// InsertedCasts - Only insert a cast in each block once.
3686 std::map<BasicBlock*, CastInst*> InsertedCasts;
3687
3688 bool MadeChange = false;
3689 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3690 UI != E; ) {
3691 Use &TheUse = UI.getUse();
3692 Instruction *User = cast<Instruction>(*UI);
3693
3694 // Figure out which BB this cast is used in. For PHI's this is the
3695 // appropriate predecessor block.
3696 BasicBlock *UserBB = User->getParent();
3697 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3698 unsigned OpVal = UI.getOperandNo()/2;
3699 UserBB = PN->getIncomingBlock(OpVal);
3700 }
3701
3702 // Preincrement use iterator so we don't invalidate it.
3703 ++UI;
3704
3705 // If this user is in the same block as the cast, don't change the cast.
3706 if (UserBB == DefBB) continue;
3707
3708 // If we have already inserted a cast into this block, use it.
3709 CastInst *&InsertedCast = InsertedCasts[UserBB];
3710
3711 if (!InsertedCast) {
3712 BasicBlock::iterator InsertPt = UserBB->begin();
3713 while (isa<PHINode>(InsertPt)) ++InsertPt;
3714
3715 InsertedCast =
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003716 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3717 InsertPt);
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003718 MadeChange = true;
3719 }
3720
3721 // Replace a use of the cast with a use of the new casat.
3722 TheUse = InsertedCast;
3723 }
3724
3725 // If we removed all uses, nuke the cast.
3726 if (CI->use_empty())
3727 CI->eraseFromParent();
3728
3729 return MadeChange;
3730}
3731
Chris Lattner35397782005-12-05 07:10:48 +00003732/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3733/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003734static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3735 Instruction *GEPI, Value *Ptr,
3736 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003737 if (V) return V; // Already computed.
3738
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003739 // Figure out the insertion point
Chris Lattner35397782005-12-05 07:10:48 +00003740 BasicBlock::iterator InsertPt;
3741 if (BB == GEPI->getParent()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003742 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattner35397782005-12-05 07:10:48 +00003743 InsertPt = GEPI;
3744 ++InsertPt;
3745 } else {
3746 // Otherwise, insert at the top of BB, after any PHI nodes
3747 InsertPt = BB->begin();
3748 while (isa<PHINode>(InsertPt)) ++InsertPt;
3749 }
3750
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003751 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3752 // BB so that there is only one value live across basic blocks (the cast
3753 // operand).
3754 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3755 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003756 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3757 "", InsertPt);
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003758
Chris Lattner35397782005-12-05 07:10:48 +00003759 // Add the offset, cast it to the right type.
3760 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003761 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3762 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3763 "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003764}
3765
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003766/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3767/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3768/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3769/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3770/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3771/// the constant add into a load or store instruction. Additionally, if a user
3772/// is a pointer-pointer cast, we look through it to find its users.
3773static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3774 Constant *PtrOffset, BasicBlock *DefBB,
3775 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003776 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003777 while (!RepPtr->use_empty()) {
3778 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003779
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003780 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3781 // used for a Pointer-Pointer cast.
3782 if (isa<BitCastInst>(User)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003783 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003784
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003785 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3786 // could invalidate an iterator.
3787 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3788 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003789 }
3790
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003791 // If this is a load of the pointer, or a store through the pointer, emit
3792 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003793 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003794 if (isa<LoadInst>(User) ||
3795 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3796 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3797 User->getParent(), GEPI,
3798 Ptr, PtrOffset);
3799 } else {
3800 // If this use is not foldable into the addressing mode, use a version
3801 // emitted in the GEP block.
3802 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3803 Ptr, PtrOffset);
3804 }
3805
Chris Lattner21cd9902006-05-06 09:10:37 +00003806 if (GEPI->getType() != RepPtr->getType()) {
3807 BasicBlock::iterator IP = NewVal;
3808 ++IP;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003809 // NewVal must be a GEP which must be pointer type, so BitCast
3810 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattner21cd9902006-05-06 09:10:37 +00003811 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003812 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003813 }
3814}
Chris Lattner35397782005-12-05 07:10:48 +00003815
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003816
Chris Lattner35397782005-12-05 07:10:48 +00003817/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3818/// selection, we want to be a bit careful about some things. In particular, if
3819/// we have a GEP instruction that is used in a different block than it is
3820/// defined, the addressing expression of the GEP cannot be folded into loads or
3821/// stores that use it. In this case, decompose the GEP and move constant
3822/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003823static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003824 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003825 // If this GEP is only used inside the block it is defined in, there is no
3826 // need to rewrite it.
3827 bool isUsedOutsideDefBB = false;
3828 BasicBlock *DefBB = GEPI->getParent();
3829 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3830 UI != E; ++UI) {
3831 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3832 isUsedOutsideDefBB = true;
3833 break;
3834 }
3835 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003836 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003837
3838 // If this GEP has no non-zero constant indices, there is nothing we can do,
3839 // ignore it.
3840 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003841 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003842 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3843 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003844 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003845 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003846 hasConstantIndex = true;
3847 break;
3848 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003849 } else {
3850 hasVariableIndex = true;
3851 }
Chris Lattner35397782005-12-05 07:10:48 +00003852 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003853
3854 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3855 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003856 /// The GEP operand must be a pointer, so must its result -> BitCast
3857 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003858 GEPI->getName(), GEPI);
3859 GEPI->replaceAllUsesWith(NC);
3860 GEPI->eraseFromParent();
3861 return true;
3862 }
3863
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003864 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003865 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3866 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003867
3868 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3869 // constant offset (which we now know is non-zero) and deal with it later.
3870 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003871 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003872 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003873 const Type *Ty = GEPI->getOperand(0)->getType();
3874
3875 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3876 E = GEPI->op_end(); OI != E; ++OI) {
3877 Value *Idx = *OI;
3878 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003879 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003880 if (Field)
Chris Lattnerc473d8e2007-02-10 19:55:17 +00003881 ConstantOffset += TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner35397782005-12-05 07:10:48 +00003882 Ty = StTy->getElementType(Field);
3883 } else {
3884 Ty = cast<SequentialType>(Ty)->getElementType();
3885
3886 // Handle constant subscripts.
3887 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003888 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00003889 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003890 continue;
3891 }
3892
3893 // Ptr = Ptr + Idx * ElementSize;
3894
3895 // Cast Idx to UIntPtrTy if needed.
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003896 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003897
Owen Anderson20a631f2006-05-03 01:29:57 +00003898 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003899 // Mask off bits that should not be set.
3900 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003901 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003902
3903 // Multiply by the element size and add to the base.
3904 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3905 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3906 }
3907 }
3908
3909 // Make sure that the offset fits in uintptr_t.
3910 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003911 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003912
3913 // Okay, we have now emitted all of the variable index parts to the BB that
3914 // the GEP is defined in. Loop over all of the using instructions, inserting
3915 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003916 // instruction to use the newly computed value, making GEPI dead. When the
3917 // user is a load or store instruction address, we emit the add into the user
3918 // block, otherwise we use a canonical version right next to the gep (these
3919 // won't be foldable as addresses, so we might as well share the computation).
3920
Chris Lattner21cd9902006-05-06 09:10:37 +00003921 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003922 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003923
3924 // Finally, the GEP is dead, remove it.
3925 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003926
3927 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003928}
3929
Chris Lattnerbba52192006-10-28 19:22:10 +00003930
3931/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3932/// successor if it will improve codegen. We only do this if the successor has
3933/// phi nodes (otherwise critical edges are ok). If there is already another
3934/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3935/// instead of introducing a new block.
3936static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3937 BasicBlock *TIBB = TI->getParent();
3938 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3939 assert(isa<PHINode>(Dest->begin()) &&
3940 "This should only be called if Dest has a PHI!");
3941
3942 /// TIPHIValues - This array is lazily computed to determine the values of
3943 /// PHIs in Dest that TI would provide.
3944 std::vector<Value*> TIPHIValues;
3945
3946 // Check to see if Dest has any blocks that can be used as a split edge for
3947 // this terminator.
3948 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3949 BasicBlock *Pred = *PI;
3950 // To be usable, the pred has to end with an uncond branch to the dest.
3951 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3952 if (!PredBr || !PredBr->isUnconditional() ||
3953 // Must be empty other than the branch.
3954 &Pred->front() != PredBr)
3955 continue;
3956
3957 // Finally, since we know that Dest has phi nodes in it, we have to make
3958 // sure that jumping to Pred will have the same affect as going to Dest in
3959 // terms of PHI values.
3960 PHINode *PN;
3961 unsigned PHINo = 0;
3962 bool FoundMatch = true;
3963 for (BasicBlock::iterator I = Dest->begin();
3964 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3965 if (PHINo == TIPHIValues.size())
3966 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3967
3968 // If the PHI entry doesn't work, we can't use this pred.
3969 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3970 FoundMatch = false;
3971 break;
3972 }
3973 }
3974
3975 // If we found a workable predecessor, change TI to branch to Succ.
3976 if (FoundMatch) {
3977 Dest->removePredecessor(TIBB);
3978 TI->setSuccessor(SuccNum, Pred);
3979 return;
3980 }
3981 }
3982
3983 SplitCriticalEdge(TI, SuccNum, P, true);
3984}
3985
3986
Chris Lattner7a60d912005-01-07 07:47:53 +00003987bool SelectionDAGISel::runOnFunction(Function &Fn) {
3988 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3989 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00003990 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00003991
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003992 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00003993 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003994 // In this pass we also look for GEP and cast instructions that are used
3995 // across basic blocks and rewrite them to improve basic-block-at-a-time
3996 // selection.
3997 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003998 bool MadeChange = true;
3999 while (MadeChange) {
4000 MadeChange = false;
Evan Chengde608342007-02-10 01:08:18 +00004001 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
Chris Lattnerbba52192006-10-28 19:22:10 +00004002 // Split all critical edges where the dest block has a PHI.
Evan Chengde608342007-02-10 01:08:18 +00004003 TerminatorInst *BBTI = FNI->getTerminator();
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004004 if (BBTI->getNumSuccessors() > 1) {
4005 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbba52192006-10-28 19:22:10 +00004006 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
4007 isCriticalEdge(BBTI, i, true))
4008 SplitEdgeNicely(BBTI, i, this);
Chris Lattner3e6b1c62006-10-28 17:04:37 +00004009 }
4010
Chris Lattner35397782005-12-05 07:10:48 +00004011
Evan Chengde608342007-02-10 01:08:18 +00004012 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004013 Instruction *I = BBI++;
Chris Lattner90f42382006-11-29 01:12:32 +00004014
4015 if (CallInst *CI = dyn_cast<CallInst>(I)) {
4016 // If we found an inline asm expession, and if the target knows how to
4017 // lower it to normal LLVM code, do so now.
4018 if (isa<InlineAsm>(CI->getCalledValue()))
4019 if (const TargetAsmInfo *TAI =
4020 TLI.getTargetMachine().getTargetAsmInfo()) {
4021 if (TAI->ExpandInlineAsm(CI))
Evan Chengde608342007-02-10 01:08:18 +00004022 BBI = FNI->begin();
Chris Lattner90f42382006-11-29 01:12:32 +00004023 }
4024 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004025 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004026 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00004027 // If the source of the cast is a constant, then this should have
4028 // already been constant folded. The only reason NOT to constant fold
4029 // it is if something (e.g. LSR) was careful to place the constant
4030 // evaluation in a block other than then one that uses it (e.g. to hoist
4031 // the address of globals out of a loop). If this is the case, we don't
4032 // want to forward-subst the cast.
4033 if (isa<Constant>(CI->getOperand(0)))
4034 continue;
4035
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004036 // If this is a noop copy, sink it into user blocks to reduce the number
4037 // of virtual registers that must be created and coallesced.
4038 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
4039 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
4040
4041 // This is an fp<->int conversion?
4042 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
4043 continue;
4044
4045 // If this is an extension, it will be a zero or sign extension, which
4046 // isn't a noop.
4047 if (SrcVT < DstVT) continue;
4048
4049 // If these values will be promoted, find out what they will be promoted
4050 // to. This helps us consider truncates on PPC as noop copies when they
4051 // are.
4052 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
4053 SrcVT = TLI.getTypeToTransformTo(SrcVT);
4054 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
4055 DstVT = TLI.getTypeToTransformTo(DstVT);
4056
4057 // If, after promotion, these are the same types, this is a noop copy.
4058 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004059 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00004060 }
4061 }
Chris Lattner1a908c82005-08-18 17:35:14 +00004062 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00004063 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00004064
Chris Lattner7a60d912005-01-07 07:47:53 +00004065 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4066
4067 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4068 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004069
Evan Cheng276b44b2007-02-10 02:43:39 +00004070 // Add function live-ins to entry block live-in set.
4071 BasicBlock *EntryBB = &Fn.getEntryBlock();
4072 BB = FuncInfo.MBBMap[EntryBB];
4073 if (!MF.livein_empty())
4074 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4075 E = MF.livein_end(); I != E; ++I)
4076 BB->addLiveIn(I->first);
4077
Chris Lattner7a60d912005-01-07 07:47:53 +00004078 return true;
4079}
4080
Chris Lattnered0110b2006-10-27 21:36:01 +00004081SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4082 unsigned Reg) {
4083 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004084 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004085 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004086 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004087
4088 // If this type is not legal, we must make sure to not create an invalid
4089 // register use.
4090 MVT::ValueType SrcVT = Op.getValueType();
4091 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004092 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004093 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004094 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004095 // Handle copies from generic vectors to registers.
4096 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004097 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004098 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004099
Chris Lattner5fe1f542006-03-31 02:06:56 +00004100 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4101 // MVT::Vector type.
4102 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4103 DAG.getConstant(NE, MVT::i32),
4104 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00004105
Chris Lattner5fe1f542006-03-31 02:06:56 +00004106 // Loop over all of the elements of the resultant vector,
4107 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4108 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004109 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004110 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004111 for (unsigned i = 0; i != NE; ++i) {
4112 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004113 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004114 if (PTyElementVT == PTyLegalElementVT) {
4115 // Elements are legal.
4116 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4117 } else if (PTyLegalElementVT > PTyElementVT) {
4118 // Elements are promoted.
4119 if (MVT::isFloatingPoint(PTyLegalElementVT))
4120 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4121 else
4122 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4123 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4124 } else {
4125 // Elements are expanded.
4126 // The src value is expanded into multiple registers.
4127 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004128 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004129 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004130 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004131 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4132 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4133 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004134 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004135 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4136 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004137 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004138 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004139 if (MVT::isFloatingPoint(SrcVT))
4140 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4141 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004142 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004143 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004144 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004145 DestVT = TLI.getTypeToExpandTo(SrcVT);
4146 unsigned NumVals = TLI.getNumElements(SrcVT);
4147 if (NumVals == 1)
4148 return DAG.getCopyToReg(getRoot(), Reg,
4149 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4150 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004151 // The src value is expanded into multiple registers.
4152 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004153 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004154 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004155 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004156 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004157 return DAG.getCopyToReg(Op, Reg+1, Hi);
4158 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004159}
4160
Chris Lattner16f64df2005-01-17 17:15:02 +00004161void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004162LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004163 std::vector<SDOperand> &UnorderedChains) {
4164 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004165 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004166 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004167 SDOperand OldRoot = SDL.DAG.getRoot();
4168 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004169
Chris Lattner6871b232005-10-30 19:42:35 +00004170 unsigned a = 0;
4171 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4172 AI != E; ++AI, ++a)
4173 if (!AI->use_empty()) {
4174 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004175
Chris Lattner6871b232005-10-30 19:42:35 +00004176 // If this argument is live outside of the entry block, insert a copy from
4177 // whereever we got it to the vreg that other BB's will reference it as.
4178 if (FuncInfo.ValueMap.count(AI)) {
4179 SDOperand Copy =
Chris Lattnered0110b2006-10-27 21:36:01 +00004180 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattner6871b232005-10-30 19:42:35 +00004181 UnorderedChains.push_back(Copy);
4182 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004183 }
Chris Lattner6871b232005-10-30 19:42:35 +00004184
Chris Lattner6871b232005-10-30 19:42:35 +00004185 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004186 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004187 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004188}
4189
Chris Lattner7a60d912005-01-07 07:47:53 +00004190void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4191 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004192 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004193 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004194
4195 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004196
Chris Lattner6871b232005-10-30 19:42:35 +00004197 // Lower any arguments needed in this block if this is the entry block.
4198 if (LLVMBB == &LLVMBB->getParent()->front())
4199 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004200
4201 BB = FuncInfo.MBBMap[LLVMBB];
4202 SDL.setCurrentBasicBlock(BB);
4203
4204 // Lower all of the non-terminator instructions.
4205 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4206 I != E; ++I)
4207 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00004208
Chris Lattner7a60d912005-01-07 07:47:53 +00004209 // Ensure that all instructions which are used outside of their defining
4210 // blocks are available as virtual registers.
4211 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00004212 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004213 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004214 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004215 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004216 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004217 }
4218
4219 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4220 // ensure constants are generated when needed. Remember the virtual registers
4221 // that need to be added to the Machine PHI nodes as input. We cannot just
4222 // directly add them, because expansion might result in multiple MBB's for one
4223 // BB. As such, the start of the BB might correspond to a different MBB than
4224 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004225 //
Chris Lattner84a03502006-10-27 23:50:33 +00004226 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004227
4228 // Emit constants only once even if used by multiple PHI nodes.
4229 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004230
Chris Lattner84a03502006-10-27 23:50:33 +00004231 // Vector bool would be better, but vector<bool> is really slow.
4232 std::vector<unsigned char> SuccsHandled;
4233 if (TI->getNumSuccessors())
4234 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4235
Chris Lattner7a60d912005-01-07 07:47:53 +00004236 // Check successor nodes PHI nodes that expect a constant to be available from
4237 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004238 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4239 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004240 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004241 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004242
Chris Lattner84a03502006-10-27 23:50:33 +00004243 // If this terminator has multiple identical successors (common for
4244 // switches), only handle each succ once.
4245 unsigned SuccMBBNo = SuccMBB->getNumber();
4246 if (SuccsHandled[SuccMBBNo]) continue;
4247 SuccsHandled[SuccMBBNo] = true;
4248
4249 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004250 PHINode *PN;
4251
4252 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4253 // nodes and Machine PHI nodes, but the incoming operands have not been
4254 // emitted yet.
4255 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004256 (PN = dyn_cast<PHINode>(I)); ++I) {
4257 // Ignore dead phi's.
4258 if (PN->use_empty()) continue;
4259
4260 unsigned Reg;
4261 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004262
Chris Lattner84a03502006-10-27 23:50:33 +00004263 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4264 unsigned &RegOut = ConstantsOut[C];
4265 if (RegOut == 0) {
4266 RegOut = FuncInfo.CreateRegForValue(C);
4267 UnorderedChains.push_back(
4268 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004269 }
Chris Lattner84a03502006-10-27 23:50:33 +00004270 Reg = RegOut;
4271 } else {
4272 Reg = FuncInfo.ValueMap[PHIOp];
4273 if (Reg == 0) {
4274 assert(isa<AllocaInst>(PHIOp) &&
4275 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4276 "Didn't codegen value into a register!??");
4277 Reg = FuncInfo.CreateRegForValue(PHIOp);
4278 UnorderedChains.push_back(
4279 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004280 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004281 }
Chris Lattner84a03502006-10-27 23:50:33 +00004282
4283 // Remember that this register needs to added to the machine PHI node as
4284 // the input for this MBB.
4285 MVT::ValueType VT = TLI.getValueType(PN->getType());
4286 unsigned NumElements;
4287 if (VT != MVT::Vector)
4288 NumElements = TLI.getNumElements(VT);
4289 else {
4290 MVT::ValueType VT1,VT2;
4291 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004292 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004293 VT1, VT2);
4294 }
4295 for (unsigned i = 0, e = NumElements; i != e; ++i)
4296 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4297 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004298 }
4299 ConstantsOut.clear();
4300
Chris Lattner718b5c22005-01-13 17:59:43 +00004301 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004302 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004303 SDOperand Root = SDL.getRoot();
4304 if (Root.getOpcode() != ISD::EntryToken) {
4305 unsigned i = 0, e = UnorderedChains.size();
4306 for (; i != e; ++i) {
4307 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4308 if (UnorderedChains[i].Val->getOperand(0) == Root)
4309 break; // Don't add the root if we already indirectly depend on it.
4310 }
4311
4312 if (i == e)
4313 UnorderedChains.push_back(Root);
4314 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004315 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4316 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004317 }
4318
Chris Lattner7a60d912005-01-07 07:47:53 +00004319 // Lower the terminator after the copies are emitted.
4320 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004321
Nate Begemaned728c12006-03-27 01:32:24 +00004322 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004323 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004324 SwitchCases.clear();
4325 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004326 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00004327
Chris Lattner4108bb02005-01-17 19:43:36 +00004328 // Make sure the root of the DAG is up-to-date.
4329 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004330}
4331
Nate Begemaned728c12006-03-27 01:32:24 +00004332void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004333 // Get alias analysis for load/store combining.
4334 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4335
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004336 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004337 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004338
Bill Wendling22e978a2006-12-07 20:04:42 +00004339 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004340 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004341
Chris Lattner7a60d912005-01-07 07:47:53 +00004342 // Second step, hack on the DAG until it only uses operations and types that
4343 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004344 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004345
Bill Wendling22e978a2006-12-07 20:04:42 +00004346 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004347 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004348
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004349 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004350 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004351
Evan Cheng739a6a42006-01-21 02:32:06 +00004352 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004353
Chris Lattner5ca31d92005-03-30 01:10:47 +00004354 // Third, instruction select all of the operations to machine code, adding the
4355 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004356 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004357
Bill Wendling22e978a2006-12-07 20:04:42 +00004358 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004359 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004360}
Chris Lattner7a60d912005-01-07 07:47:53 +00004361
Nate Begemaned728c12006-03-27 01:32:24 +00004362void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4363 FunctionLoweringInfo &FuncInfo) {
4364 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4365 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004366 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004367 CurDAG = &DAG;
4368
4369 // First step, lower LLVM code to some DAG. This DAG may use operations and
4370 // types that are not supported by the target.
4371 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4372
4373 // Second step, emit the lowered DAG as machine code.
4374 CodeGenAndEmitDAG(DAG);
4375 }
4376
Chris Lattner5ca31d92005-03-30 01:10:47 +00004377 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004378 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004379 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00004380 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4381 MachineInstr *PHI = PHINodesToUpdate[i].first;
4382 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4383 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004384 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004385 PHI->addMachineBasicBlockOperand(BB);
4386 }
4387 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004388 }
Nate Begemaned728c12006-03-27 01:32:24 +00004389
Nate Begeman866b4b42006-04-23 06:26:20 +00004390 // If the JumpTable record is filled in, then we need to emit a jump table.
4391 // Updating the PHI nodes is tricky in this case, since we need to determine
4392 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004393 if (JT.Reg) {
4394 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
Jim Laskeyc56315c2007-01-26 21:22:28 +00004395 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004396 CurDAG = &SDAG;
4397 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00004398 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004399 // Set the current basic block to the mbb we wish to insert the code into
4400 BB = JT.MBB;
4401 SDL.setCurrentBasicBlock(BB);
4402 // Emit the code
4403 SDL.visitJumpTable(JT);
4404 SDAG.setRoot(SDL.getRoot());
4405 CodeGenAndEmitDAG(SDAG);
4406 // Update PHI Nodes
4407 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4408 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4409 MachineBasicBlock *PHIBB = PHI->getParent();
4410 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4411 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00004412 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004413 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004414 PHI->addMachineBasicBlockOperand(RangeBB);
4415 }
4416 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004417 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004418 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004419 }
4420 }
4421 return;
4422 }
4423
Chris Lattner76a7bc82006-10-22 23:00:53 +00004424 // If the switch block involved a branch to one of the actual successors, we
4425 // need to update PHI nodes in that block.
4426 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4427 MachineInstr *PHI = PHINodesToUpdate[i].first;
4428 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4429 "This is not a machine PHI node that we are updating!");
4430 if (BB->isSuccessor(PHI->getParent())) {
4431 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4432 PHI->addMachineBasicBlockOperand(BB);
4433 }
4434 }
4435
Nate Begemaned728c12006-03-27 01:32:24 +00004436 // If we generated any switch lowering information, build and codegen any
4437 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004438 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004439 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004440 CurDAG = &SDAG;
4441 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004442
Nate Begemaned728c12006-03-27 01:32:24 +00004443 // Set the current basic block to the mbb we wish to insert the code into
4444 BB = SwitchCases[i].ThisBB;
4445 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004446
Nate Begemaned728c12006-03-27 01:32:24 +00004447 // Emit the code
4448 SDL.visitSwitchCase(SwitchCases[i]);
4449 SDAG.setRoot(SDL.getRoot());
4450 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004451
4452 // Handle any PHI nodes in successors of this chunk, as if we were coming
4453 // from the original BB before switch expansion. Note that PHI nodes can
4454 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4455 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004456 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004457 for (MachineBasicBlock::iterator Phi = BB->begin();
4458 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4459 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4460 for (unsigned pn = 0; ; ++pn) {
4461 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4462 if (PHINodesToUpdate[pn].first == Phi) {
4463 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4464 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4465 break;
4466 }
4467 }
Nate Begemaned728c12006-03-27 01:32:24 +00004468 }
Chris Lattner707339a52006-09-07 01:59:34 +00004469
4470 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004471 if (BB == SwitchCases[i].FalseBB)
4472 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004473
4474 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004475 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004476 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004477 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004478 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004479 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004480}
Evan Cheng739a6a42006-01-21 02:32:06 +00004481
Jim Laskey95eda5b2006-08-01 14:21:23 +00004482
Evan Cheng739a6a42006-01-21 02:32:06 +00004483//===----------------------------------------------------------------------===//
4484/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4485/// target node in the graph.
4486void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4487 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004488
Jim Laskey29e635d2006-08-02 12:30:23 +00004489 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004490
4491 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004492 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004493 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004494 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004495
Jim Laskey03593f72006-08-01 18:29:48 +00004496 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004497 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004498 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004499}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004500
Chris Lattner47639db2006-03-06 00:22:00 +00004501
Jim Laskey03593f72006-08-01 18:29:48 +00004502HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4503 return new HazardRecognizer();
4504}
4505
Chris Lattner6df34962006-10-11 03:58:02 +00004506//===----------------------------------------------------------------------===//
4507// Helper functions used by the generated instruction selector.
4508//===----------------------------------------------------------------------===//
4509// Calls to these methods are generated by tblgen.
4510
4511/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4512/// the dag combiner simplified the 255, we still want to match. RHS is the
4513/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4514/// specified in the .td file (e.g. 255).
4515bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4516 int64_t DesiredMaskS) {
4517 uint64_t ActualMask = RHS->getValue();
4518 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4519
4520 // If the actual mask exactly matches, success!
4521 if (ActualMask == DesiredMask)
4522 return true;
4523
4524 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4525 if (ActualMask & ~DesiredMask)
4526 return false;
4527
4528 // Otherwise, the DAG Combiner may have proven that the value coming in is
4529 // either already zero or is not demanded. Check for known zero input bits.
4530 uint64_t NeededMask = DesiredMask & ~ActualMask;
4531 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4532 return true;
4533
4534 // TODO: check to see if missing bits are just not demanded.
4535
4536 // Otherwise, this pattern doesn't match.
4537 return false;
4538}
4539
4540/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4541/// the dag combiner simplified the 255, we still want to match. RHS is the
4542/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4543/// specified in the .td file (e.g. 255).
4544bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4545 int64_t DesiredMaskS) {
4546 uint64_t ActualMask = RHS->getValue();
4547 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4548
4549 // If the actual mask exactly matches, success!
4550 if (ActualMask == DesiredMask)
4551 return true;
4552
4553 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4554 if (ActualMask & ~DesiredMask)
4555 return false;
4556
4557 // Otherwise, the DAG Combiner may have proven that the value coming in is
4558 // either already zero or is not demanded. Check for known zero input bits.
4559 uint64_t NeededMask = DesiredMask & ~ActualMask;
4560
4561 uint64_t KnownZero, KnownOne;
4562 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4563
4564 // If all the missing bits in the or are already known to be set, match!
4565 if ((NeededMask & KnownOne) == NeededMask)
4566 return true;
4567
4568 // TODO: check to see if missing bits are just not demanded.
4569
4570 // Otherwise, this pattern doesn't match.
4571 return false;
4572}
4573
Jim Laskey03593f72006-08-01 18:29:48 +00004574
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004575/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4576/// by tblgen. Others should not call it.
4577void SelectionDAGISel::
4578SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4579 std::vector<SDOperand> InOps;
4580 std::swap(InOps, Ops);
4581
4582 Ops.push_back(InOps[0]); // input chain.
4583 Ops.push_back(InOps[1]); // input asm string.
4584
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004585 unsigned i = 2, e = InOps.size();
4586 if (InOps[e-1].getValueType() == MVT::Flag)
4587 --e; // Don't process a flag operand if it is here.
4588
4589 while (i != e) {
4590 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4591 if ((Flags & 7) != 4 /*MEM*/) {
4592 // Just skip over this operand, copying the operands verbatim.
4593 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4594 i += (Flags >> 3) + 1;
4595 } else {
4596 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4597 // Otherwise, this is a memory operand. Ask the target to select it.
4598 std::vector<SDOperand> SelOps;
4599 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004600 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004601 exit(1);
4602 }
4603
4604 // Add this to the output node.
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004605 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4606 MVT::i32));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004607 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4608 i += 2;
4609 }
4610 }
4611
4612 // Add the flag input back if present.
4613 if (e != InOps.size())
4614 Ops.push_back(InOps.back());
4615}