1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLParser.h"
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
getTypeString(Type * T)29 static std::string getTypeString(Type *T) {
30 std::string Result;
31 raw_string_ostream Tmp(Result);
32 Tmp << *T;
33 return Tmp.str();
34 }
35
36 /// Run: module ::= toplevelentity*
Run()37 bool LLParser::Run() {
38 // Prime the lexer.
39 Lex.Lex();
40
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
43 }
44
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
46 /// module.
ValidateEndOfModule()47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
52 I != E; ++I) {
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
55
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
58
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
61 Twine(SlotNo) + "'");
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
63 }
64 }
65 ForwardRefInstMetadata.clear();
66 }
67
68
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
73 Function *TheFn = 0;
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
79
80 if (TheFn == 0)
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
82
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
86 0))
87 return true;
88
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
90 }
91
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
96
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
102
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
106 "'");
107
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
112
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
117
118
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
122
123 // Check debug info intrinsics.
124 CheckDebugInfoIntrinsics(M);
125 return false;
126 }
127
ResolveForwardRefBlockAddresses(Function * TheFn,std::vector<std::pair<ValID,GlobalValue * >> & Refs,PerFunctionState * PFS)128 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
129 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
130 PerFunctionState *PFS) {
131 // Loop over all the references, resolving them.
132 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 BasicBlock *Res;
134 if (PFS) {
135 if (Refs[i].first.Kind == ValID::t_LocalName)
136 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
137 else
138 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
139 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
140 return Error(Refs[i].first.Loc,
141 "cannot take address of numeric label after the function is defined");
142 } else {
143 Res = dyn_cast_or_null<BasicBlock>(
144 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
145 }
146
147 if (Res == 0)
148 return Error(Refs[i].first.Loc,
149 "referenced value is not a basic block");
150
151 // Get the BlockAddress for this and update references to use it.
152 BlockAddress *BA = BlockAddress::get(TheFn, Res);
153 Refs[i].second->replaceAllUsesWith(BA);
154 Refs[i].second->eraseFromParent();
155 }
156 return false;
157 }
158
159
160 //===----------------------------------------------------------------------===//
161 // Top-Level Entities
162 //===----------------------------------------------------------------------===//
163
ParseTopLevelEntities()164 bool LLParser::ParseTopLevelEntities() {
165 while (1) {
166 switch (Lex.getKind()) {
167 default: return TokError("expected top-level entity");
168 case lltok::Eof: return false;
169 case lltok::kw_declare: if (ParseDeclare()) return true; break;
170 case lltok::kw_define: if (ParseDefine()) return true; break;
171 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
172 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
173 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
174 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
175 case lltok::LocalVar: if (ParseNamedType()) return true; break;
176 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
177 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
178 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
179 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
180
181 // The Global variable production with no name can have many different
182 // optional leading prefixes, the production is:
183 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
184 // OptionalAddrSpace OptionalUnNammedAddr
185 // ('constant'|'global') ...
186 case lltok::kw_private: // OptionalLinkage
187 case lltok::kw_linker_private: // OptionalLinkage
188 case lltok::kw_linker_private_weak: // OptionalLinkage
189 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
190 case lltok::kw_internal: // OptionalLinkage
191 case lltok::kw_weak: // OptionalLinkage
192 case lltok::kw_weak_odr: // OptionalLinkage
193 case lltok::kw_linkonce: // OptionalLinkage
194 case lltok::kw_linkonce_odr: // OptionalLinkage
195 case lltok::kw_appending: // OptionalLinkage
196 case lltok::kw_dllexport: // OptionalLinkage
197 case lltok::kw_common: // OptionalLinkage
198 case lltok::kw_dllimport: // OptionalLinkage
199 case lltok::kw_extern_weak: // OptionalLinkage
200 case lltok::kw_external: { // OptionalLinkage
201 unsigned Linkage, Visibility;
202 if (ParseOptionalLinkage(Linkage) ||
203 ParseOptionalVisibility(Visibility) ||
204 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
205 return true;
206 break;
207 }
208 case lltok::kw_default: // OptionalVisibility
209 case lltok::kw_hidden: // OptionalVisibility
210 case lltok::kw_protected: { // OptionalVisibility
211 unsigned Visibility;
212 if (ParseOptionalVisibility(Visibility) ||
213 ParseGlobal("", SMLoc(), 0, false, Visibility))
214 return true;
215 break;
216 }
217
218 case lltok::kw_thread_local: // OptionalThreadLocal
219 case lltok::kw_addrspace: // OptionalAddrSpace
220 case lltok::kw_constant: // GlobalType
221 case lltok::kw_global: // GlobalType
222 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
223 break;
224 }
225 }
226 }
227
228
229 /// toplevelentity
230 /// ::= 'module' 'asm' STRINGCONSTANT
ParseModuleAsm()231 bool LLParser::ParseModuleAsm() {
232 assert(Lex.getKind() == lltok::kw_module);
233 Lex.Lex();
234
235 std::string AsmStr;
236 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
237 ParseStringConstant(AsmStr)) return true;
238
239 M->appendModuleInlineAsm(AsmStr);
240 return false;
241 }
242
243 /// toplevelentity
244 /// ::= 'target' 'triple' '=' STRINGCONSTANT
245 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
ParseTargetDefinition()246 bool LLParser::ParseTargetDefinition() {
247 assert(Lex.getKind() == lltok::kw_target);
248 std::string Str;
249 switch (Lex.Lex()) {
250 default: return TokError("unknown target property");
251 case lltok::kw_triple:
252 Lex.Lex();
253 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
254 ParseStringConstant(Str))
255 return true;
256 M->setTargetTriple(Str);
257 return false;
258 case lltok::kw_datalayout:
259 Lex.Lex();
260 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
261 ParseStringConstant(Str))
262 return true;
263 M->setDataLayout(Str);
264 return false;
265 }
266 }
267
268 /// toplevelentity
269 /// ::= 'deplibs' '=' '[' ']'
270 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
ParseDepLibs()271 bool LLParser::ParseDepLibs() {
272 assert(Lex.getKind() == lltok::kw_deplibs);
273 Lex.Lex();
274 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
275 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
276 return true;
277
278 if (EatIfPresent(lltok::rsquare))
279 return false;
280
281 std::string Str;
282 if (ParseStringConstant(Str)) return true;
283 M->addLibrary(Str);
284
285 while (EatIfPresent(lltok::comma)) {
286 if (ParseStringConstant(Str)) return true;
287 M->addLibrary(Str);
288 }
289
290 return ParseToken(lltok::rsquare, "expected ']' at end of list");
291 }
292
293 /// ParseUnnamedType:
294 /// ::= LocalVarID '=' 'type' type
ParseUnnamedType()295 bool LLParser::ParseUnnamedType() {
296 LocTy TypeLoc = Lex.getLoc();
297 unsigned TypeID = Lex.getUIntVal();
298 Lex.Lex(); // eat LocalVarID;
299
300 if (ParseToken(lltok::equal, "expected '=' after name") ||
301 ParseToken(lltok::kw_type, "expected 'type' after '='"))
302 return true;
303
304 if (TypeID >= NumberedTypes.size())
305 NumberedTypes.resize(TypeID+1);
306
307 Type *Result = 0;
308 if (ParseStructDefinition(TypeLoc, "",
309 NumberedTypes[TypeID], Result)) return true;
310
311 if (!isa<StructType>(Result)) {
312 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
313 if (Entry.first)
314 return Error(TypeLoc, "non-struct types may not be recursive");
315 Entry.first = Result;
316 Entry.second = SMLoc();
317 }
318
319 return false;
320 }
321
322
323 /// toplevelentity
324 /// ::= LocalVar '=' 'type' type
ParseNamedType()325 bool LLParser::ParseNamedType() {
326 std::string Name = Lex.getStrVal();
327 LocTy NameLoc = Lex.getLoc();
328 Lex.Lex(); // eat LocalVar.
329
330 if (ParseToken(lltok::equal, "expected '=' after name") ||
331 ParseToken(lltok::kw_type, "expected 'type' after name"))
332 return true;
333
334 Type *Result = 0;
335 if (ParseStructDefinition(NameLoc, Name,
336 NamedTypes[Name], Result)) return true;
337
338 if (!isa<StructType>(Result)) {
339 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
340 if (Entry.first)
341 return Error(NameLoc, "non-struct types may not be recursive");
342 Entry.first = Result;
343 Entry.second = SMLoc();
344 }
345
346 return false;
347 }
348
349
350 /// toplevelentity
351 /// ::= 'declare' FunctionHeader
ParseDeclare()352 bool LLParser::ParseDeclare() {
353 assert(Lex.getKind() == lltok::kw_declare);
354 Lex.Lex();
355
356 Function *F;
357 return ParseFunctionHeader(F, false);
358 }
359
360 /// toplevelentity
361 /// ::= 'define' FunctionHeader '{' ...
ParseDefine()362 bool LLParser::ParseDefine() {
363 assert(Lex.getKind() == lltok::kw_define);
364 Lex.Lex();
365
366 Function *F;
367 return ParseFunctionHeader(F, true) ||
368 ParseFunctionBody(*F);
369 }
370
371 /// ParseGlobalType
372 /// ::= 'constant'
373 /// ::= 'global'
ParseGlobalType(bool & IsConstant)374 bool LLParser::ParseGlobalType(bool &IsConstant) {
375 if (Lex.getKind() == lltok::kw_constant)
376 IsConstant = true;
377 else if (Lex.getKind() == lltok::kw_global)
378 IsConstant = false;
379 else {
380 IsConstant = false;
381 return TokError("expected 'global' or 'constant'");
382 }
383 Lex.Lex();
384 return false;
385 }
386
387 /// ParseUnnamedGlobal:
388 /// OptionalVisibility ALIAS ...
389 /// OptionalLinkage OptionalVisibility ... -> global variable
390 /// GlobalID '=' OptionalVisibility ALIAS ...
391 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
ParseUnnamedGlobal()392 bool LLParser::ParseUnnamedGlobal() {
393 unsigned VarID = NumberedVals.size();
394 std::string Name;
395 LocTy NameLoc = Lex.getLoc();
396
397 // Handle the GlobalID form.
398 if (Lex.getKind() == lltok::GlobalID) {
399 if (Lex.getUIntVal() != VarID)
400 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
401 Twine(VarID) + "'");
402 Lex.Lex(); // eat GlobalID;
403
404 if (ParseToken(lltok::equal, "expected '=' after name"))
405 return true;
406 }
407
408 bool HasLinkage;
409 unsigned Linkage, Visibility;
410 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
411 ParseOptionalVisibility(Visibility))
412 return true;
413
414 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
415 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
416 return ParseAlias(Name, NameLoc, Visibility);
417 }
418
419 /// ParseNamedGlobal:
420 /// GlobalVar '=' OptionalVisibility ALIAS ...
421 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
ParseNamedGlobal()422 bool LLParser::ParseNamedGlobal() {
423 assert(Lex.getKind() == lltok::GlobalVar);
424 LocTy NameLoc = Lex.getLoc();
425 std::string Name = Lex.getStrVal();
426 Lex.Lex();
427
428 bool HasLinkage;
429 unsigned Linkage, Visibility;
430 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
431 ParseOptionalLinkage(Linkage, HasLinkage) ||
432 ParseOptionalVisibility(Visibility))
433 return true;
434
435 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
436 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
437 return ParseAlias(Name, NameLoc, Visibility);
438 }
439
440 // MDString:
441 // ::= '!' STRINGCONSTANT
ParseMDString(MDString * & Result)442 bool LLParser::ParseMDString(MDString *&Result) {
443 std::string Str;
444 if (ParseStringConstant(Str)) return true;
445 Result = MDString::get(Context, Str);
446 return false;
447 }
448
449 // MDNode:
450 // ::= '!' MDNodeNumber
451 //
452 /// This version of ParseMDNodeID returns the slot number and null in the case
453 /// of a forward reference.
ParseMDNodeID(MDNode * & Result,unsigned & SlotNo)454 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
455 // !{ ..., !42, ... }
456 if (ParseUInt32(SlotNo)) return true;
457
458 // Check existing MDNode.
459 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
460 Result = NumberedMetadata[SlotNo];
461 else
462 Result = 0;
463 return false;
464 }
465
ParseMDNodeID(MDNode * & Result)466 bool LLParser::ParseMDNodeID(MDNode *&Result) {
467 // !{ ..., !42, ... }
468 unsigned MID = 0;
469 if (ParseMDNodeID(Result, MID)) return true;
470
471 // If not a forward reference, just return it now.
472 if (Result) return false;
473
474 // Otherwise, create MDNode forward reference.
475 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
476 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
477
478 if (NumberedMetadata.size() <= MID)
479 NumberedMetadata.resize(MID+1);
480 NumberedMetadata[MID] = FwdNode;
481 Result = FwdNode;
482 return false;
483 }
484
485 /// ParseNamedMetadata:
486 /// !foo = !{ !1, !2 }
ParseNamedMetadata()487 bool LLParser::ParseNamedMetadata() {
488 assert(Lex.getKind() == lltok::MetadataVar);
489 std::string Name = Lex.getStrVal();
490 Lex.Lex();
491
492 if (ParseToken(lltok::equal, "expected '=' here") ||
493 ParseToken(lltok::exclaim, "Expected '!' here") ||
494 ParseToken(lltok::lbrace, "Expected '{' here"))
495 return true;
496
497 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
498 if (Lex.getKind() != lltok::rbrace)
499 do {
500 if (ParseToken(lltok::exclaim, "Expected '!' here"))
501 return true;
502
503 MDNode *N = 0;
504 if (ParseMDNodeID(N)) return true;
505 NMD->addOperand(N);
506 } while (EatIfPresent(lltok::comma));
507
508 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
509 return true;
510
511 return false;
512 }
513
514 /// ParseStandaloneMetadata:
515 /// !42 = !{...}
ParseStandaloneMetadata()516 bool LLParser::ParseStandaloneMetadata() {
517 assert(Lex.getKind() == lltok::exclaim);
518 Lex.Lex();
519 unsigned MetadataID = 0;
520
521 LocTy TyLoc;
522 Type *Ty = 0;
523 SmallVector<Value *, 16> Elts;
524 if (ParseUInt32(MetadataID) ||
525 ParseToken(lltok::equal, "expected '=' here") ||
526 ParseType(Ty, TyLoc) ||
527 ParseToken(lltok::exclaim, "Expected '!' here") ||
528 ParseToken(lltok::lbrace, "Expected '{' here") ||
529 ParseMDNodeVector(Elts, NULL) ||
530 ParseToken(lltok::rbrace, "expected end of metadata node"))
531 return true;
532
533 MDNode *Init = MDNode::get(Context, Elts);
534
535 // See if this was forward referenced, if so, handle it.
536 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
537 FI = ForwardRefMDNodes.find(MetadataID);
538 if (FI != ForwardRefMDNodes.end()) {
539 MDNode *Temp = FI->second.first;
540 Temp->replaceAllUsesWith(Init);
541 MDNode::deleteTemporary(Temp);
542 ForwardRefMDNodes.erase(FI);
543
544 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
545 } else {
546 if (MetadataID >= NumberedMetadata.size())
547 NumberedMetadata.resize(MetadataID+1);
548
549 if (NumberedMetadata[MetadataID] != 0)
550 return TokError("Metadata id is already used");
551 NumberedMetadata[MetadataID] = Init;
552 }
553
554 return false;
555 }
556
557 /// ParseAlias:
558 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
559 /// Aliasee
560 /// ::= TypeAndValue
561 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
562 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
563 ///
564 /// Everything through visibility has already been parsed.
565 ///
ParseAlias(const std::string & Name,LocTy NameLoc,unsigned Visibility)566 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
567 unsigned Visibility) {
568 assert(Lex.getKind() == lltok::kw_alias);
569 Lex.Lex();
570 unsigned Linkage;
571 LocTy LinkageLoc = Lex.getLoc();
572 if (ParseOptionalLinkage(Linkage))
573 return true;
574
575 if (Linkage != GlobalValue::ExternalLinkage &&
576 Linkage != GlobalValue::WeakAnyLinkage &&
577 Linkage != GlobalValue::WeakODRLinkage &&
578 Linkage != GlobalValue::InternalLinkage &&
579 Linkage != GlobalValue::PrivateLinkage &&
580 Linkage != GlobalValue::LinkerPrivateLinkage &&
581 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
582 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
583 return Error(LinkageLoc, "invalid linkage type for alias");
584
585 Constant *Aliasee;
586 LocTy AliaseeLoc = Lex.getLoc();
587 if (Lex.getKind() != lltok::kw_bitcast &&
588 Lex.getKind() != lltok::kw_getelementptr) {
589 if (ParseGlobalTypeAndValue(Aliasee)) return true;
590 } else {
591 // The bitcast dest type is not present, it is implied by the dest type.
592 ValID ID;
593 if (ParseValID(ID)) return true;
594 if (ID.Kind != ValID::t_Constant)
595 return Error(AliaseeLoc, "invalid aliasee");
596 Aliasee = ID.ConstantVal;
597 }
598
599 if (!Aliasee->getType()->isPointerTy())
600 return Error(AliaseeLoc, "alias must have pointer type");
601
602 // Okay, create the alias but do not insert it into the module yet.
603 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
604 (GlobalValue::LinkageTypes)Linkage, Name,
605 Aliasee);
606 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
607
608 // See if this value already exists in the symbol table. If so, it is either
609 // a redefinition or a definition of a forward reference.
610 if (GlobalValue *Val = M->getNamedValue(Name)) {
611 // See if this was a redefinition. If so, there is no entry in
612 // ForwardRefVals.
613 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
614 I = ForwardRefVals.find(Name);
615 if (I == ForwardRefVals.end())
616 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
617
618 // Otherwise, this was a definition of forward ref. Verify that types
619 // agree.
620 if (Val->getType() != GA->getType())
621 return Error(NameLoc,
622 "forward reference and definition of alias have different types");
623
624 // If they agree, just RAUW the old value with the alias and remove the
625 // forward ref info.
626 Val->replaceAllUsesWith(GA);
627 Val->eraseFromParent();
628 ForwardRefVals.erase(I);
629 }
630
631 // Insert into the module, we know its name won't collide now.
632 M->getAliasList().push_back(GA);
633 assert(GA->getName() == Name && "Should not be a name conflict!");
634
635 return false;
636 }
637
638 /// ParseGlobal
639 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
640 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
641 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
642 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
643 ///
644 /// Everything through visibility has been parsed already.
645 ///
ParseGlobal(const std::string & Name,LocTy NameLoc,unsigned Linkage,bool HasLinkage,unsigned Visibility)646 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
647 unsigned Linkage, bool HasLinkage,
648 unsigned Visibility) {
649 unsigned AddrSpace;
650 bool ThreadLocal, IsConstant, UnnamedAddr;
651 LocTy UnnamedAddrLoc;
652 LocTy TyLoc;
653
654 Type *Ty = 0;
655 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
656 ParseOptionalAddrSpace(AddrSpace) ||
657 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
658 &UnnamedAddrLoc) ||
659 ParseGlobalType(IsConstant) ||
660 ParseType(Ty, TyLoc))
661 return true;
662
663 // If the linkage is specified and is external, then no initializer is
664 // present.
665 Constant *Init = 0;
666 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
667 Linkage != GlobalValue::ExternalWeakLinkage &&
668 Linkage != GlobalValue::ExternalLinkage)) {
669 if (ParseGlobalValue(Ty, Init))
670 return true;
671 }
672
673 if (Ty->isFunctionTy() || Ty->isLabelTy())
674 return Error(TyLoc, "invalid type for global variable");
675
676 GlobalVariable *GV = 0;
677
678 // See if the global was forward referenced, if so, use the global.
679 if (!Name.empty()) {
680 if (GlobalValue *GVal = M->getNamedValue(Name)) {
681 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
682 return Error(NameLoc, "redefinition of global '@" + Name + "'");
683 GV = cast<GlobalVariable>(GVal);
684 }
685 } else {
686 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
687 I = ForwardRefValIDs.find(NumberedVals.size());
688 if (I != ForwardRefValIDs.end()) {
689 GV = cast<GlobalVariable>(I->second.first);
690 ForwardRefValIDs.erase(I);
691 }
692 }
693
694 if (GV == 0) {
695 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
696 Name, 0, false, AddrSpace);
697 } else {
698 if (GV->getType()->getElementType() != Ty)
699 return Error(TyLoc,
700 "forward reference and definition of global have different types");
701
702 // Move the forward-reference to the correct spot in the module.
703 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
704 }
705
706 if (Name.empty())
707 NumberedVals.push_back(GV);
708
709 // Set the parsed properties on the global.
710 if (Init)
711 GV->setInitializer(Init);
712 GV->setConstant(IsConstant);
713 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
714 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
715 GV->setThreadLocal(ThreadLocal);
716 GV->setUnnamedAddr(UnnamedAddr);
717
718 // Parse attributes on the global.
719 while (Lex.getKind() == lltok::comma) {
720 Lex.Lex();
721
722 if (Lex.getKind() == lltok::kw_section) {
723 Lex.Lex();
724 GV->setSection(Lex.getStrVal());
725 if (ParseToken(lltok::StringConstant, "expected global section string"))
726 return true;
727 } else if (Lex.getKind() == lltok::kw_align) {
728 unsigned Alignment;
729 if (ParseOptionalAlignment(Alignment)) return true;
730 GV->setAlignment(Alignment);
731 } else {
732 TokError("unknown global variable property!");
733 }
734 }
735
736 return false;
737 }
738
739
740 //===----------------------------------------------------------------------===//
741 // GlobalValue Reference/Resolution Routines.
742 //===----------------------------------------------------------------------===//
743
744 /// GetGlobalVal - Get a value with the specified name or ID, creating a
745 /// forward reference record if needed. This can return null if the value
746 /// exists but does not have the right type.
GetGlobalVal(const std::string & Name,Type * Ty,LocTy Loc)747 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
748 LocTy Loc) {
749 PointerType *PTy = dyn_cast<PointerType>(Ty);
750 if (PTy == 0) {
751 Error(Loc, "global variable reference must have pointer type");
752 return 0;
753 }
754
755 // Look this name up in the normal function symbol table.
756 GlobalValue *Val =
757 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
758
759 // If this is a forward reference for the value, see if we already created a
760 // forward ref record.
761 if (Val == 0) {
762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefVals.find(Name);
764 if (I != ForwardRefVals.end())
765 Val = I->second.first;
766 }
767
768 // If we have the value in the symbol table or fwd-ref table, return it.
769 if (Val) {
770 if (Val->getType() == Ty) return Val;
771 Error(Loc, "'@" + Name + "' defined with type '" +
772 getTypeString(Val->getType()) + "'");
773 return 0;
774 }
775
776 // Otherwise, create a new forward reference for this value and remember it.
777 GlobalValue *FwdVal;
778 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
779 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
780 else
781 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
782 GlobalValue::ExternalWeakLinkage, 0, Name);
783
784 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
785 return FwdVal;
786 }
787
GetGlobalVal(unsigned ID,Type * Ty,LocTy Loc)788 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
789 PointerType *PTy = dyn_cast<PointerType>(Ty);
790 if (PTy == 0) {
791 Error(Loc, "global variable reference must have pointer type");
792 return 0;
793 }
794
795 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
796
797 // If this is a forward reference for the value, see if we already created a
798 // forward ref record.
799 if (Val == 0) {
800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
801 I = ForwardRefValIDs.find(ID);
802 if (I != ForwardRefValIDs.end())
803 Val = I->second.first;
804 }
805
806 // If we have the value in the symbol table or fwd-ref table, return it.
807 if (Val) {
808 if (Val->getType() == Ty) return Val;
809 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
810 getTypeString(Val->getType()) + "'");
811 return 0;
812 }
813
814 // Otherwise, create a new forward reference for this value and remember it.
815 GlobalValue *FwdVal;
816 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
817 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
818 else
819 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
820 GlobalValue::ExternalWeakLinkage, 0, "");
821
822 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
823 return FwdVal;
824 }
825
826
827 //===----------------------------------------------------------------------===//
828 // Helper Routines.
829 //===----------------------------------------------------------------------===//
830
831 /// ParseToken - If the current token has the specified kind, eat it and return
832 /// success. Otherwise, emit the specified error and return failure.
ParseToken(lltok::Kind T,const char * ErrMsg)833 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
834 if (Lex.getKind() != T)
835 return TokError(ErrMsg);
836 Lex.Lex();
837 return false;
838 }
839
840 /// ParseStringConstant
841 /// ::= StringConstant
ParseStringConstant(std::string & Result)842 bool LLParser::ParseStringConstant(std::string &Result) {
843 if (Lex.getKind() != lltok::StringConstant)
844 return TokError("expected string constant");
845 Result = Lex.getStrVal();
846 Lex.Lex();
847 return false;
848 }
849
850 /// ParseUInt32
851 /// ::= uint32
ParseUInt32(unsigned & Val)852 bool LLParser::ParseUInt32(unsigned &Val) {
853 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
854 return TokError("expected integer");
855 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
856 if (Val64 != unsigned(Val64))
857 return TokError("expected 32-bit integer (too large)");
858 Val = Val64;
859 Lex.Lex();
860 return false;
861 }
862
863
864 /// ParseOptionalAddrSpace
865 /// := /*empty*/
866 /// := 'addrspace' '(' uint32 ')'
ParseOptionalAddrSpace(unsigned & AddrSpace)867 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
868 AddrSpace = 0;
869 if (!EatIfPresent(lltok::kw_addrspace))
870 return false;
871 return ParseToken(lltok::lparen, "expected '(' in address space") ||
872 ParseUInt32(AddrSpace) ||
873 ParseToken(lltok::rparen, "expected ')' in address space");
874 }
875
876 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
877 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
878 /// 2: function attr.
ParseOptionalAttrs(unsigned & Attrs,unsigned AttrKind)879 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
880 Attrs = Attribute::None;
881 LocTy AttrLoc = Lex.getLoc();
882
883 while (1) {
884 switch (Lex.getKind()) {
885 default: // End of attributes.
886 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
887 return Error(AttrLoc, "invalid use of function-only attribute");
888
889 // As a hack, we allow "align 2" on functions as a synonym for
890 // "alignstack 2".
891 if (AttrKind == 2 &&
892 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
893 return Error(AttrLoc, "invalid use of attribute on a function");
894
895 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
896 return Error(AttrLoc, "invalid use of parameter-only attribute");
897
898 return false;
899 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
900 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
901 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
902 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
903 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
904 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
905 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
906 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
907
908 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
909 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
910 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
911 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
912 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
913 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
914 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
915 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
916 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
917 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
918 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
919 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
920 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
921 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
922 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
923 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
924
925 case lltok::kw_alignstack: {
926 unsigned Alignment;
927 if (ParseOptionalStackAlignment(Alignment))
928 return true;
929 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
930 continue;
931 }
932
933 case lltok::kw_align: {
934 unsigned Alignment;
935 if (ParseOptionalAlignment(Alignment))
936 return true;
937 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
938 continue;
939 }
940
941 }
942 Lex.Lex();
943 }
944 }
945
946 /// ParseOptionalLinkage
947 /// ::= /*empty*/
948 /// ::= 'private'
949 /// ::= 'linker_private'
950 /// ::= 'linker_private_weak'
951 /// ::= 'linker_private_weak_def_auto'
952 /// ::= 'internal'
953 /// ::= 'weak'
954 /// ::= 'weak_odr'
955 /// ::= 'linkonce'
956 /// ::= 'linkonce_odr'
957 /// ::= 'available_externally'
958 /// ::= 'appending'
959 /// ::= 'dllexport'
960 /// ::= 'common'
961 /// ::= 'dllimport'
962 /// ::= 'extern_weak'
963 /// ::= 'external'
ParseOptionalLinkage(unsigned & Res,bool & HasLinkage)964 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
965 HasLinkage = false;
966 switch (Lex.getKind()) {
967 default: Res=GlobalValue::ExternalLinkage; return false;
968 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
969 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
970 case lltok::kw_linker_private_weak:
971 Res = GlobalValue::LinkerPrivateWeakLinkage;
972 break;
973 case lltok::kw_linker_private_weak_def_auto:
974 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
975 break;
976 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
977 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
978 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
979 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
980 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
981 case lltok::kw_available_externally:
982 Res = GlobalValue::AvailableExternallyLinkage;
983 break;
984 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
985 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
986 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
987 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
988 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
989 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
990 }
991 Lex.Lex();
992 HasLinkage = true;
993 return false;
994 }
995
996 /// ParseOptionalVisibility
997 /// ::= /*empty*/
998 /// ::= 'default'
999 /// ::= 'hidden'
1000 /// ::= 'protected'
1001 ///
ParseOptionalVisibility(unsigned & Res)1002 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1003 switch (Lex.getKind()) {
1004 default: Res = GlobalValue::DefaultVisibility; return false;
1005 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1006 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1007 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1008 }
1009 Lex.Lex();
1010 return false;
1011 }
1012
1013 /// ParseOptionalCallingConv
1014 /// ::= /*empty*/
1015 /// ::= 'ccc'
1016 /// ::= 'fastcc'
1017 /// ::= 'coldcc'
1018 /// ::= 'x86_stdcallcc'
1019 /// ::= 'x86_fastcallcc'
1020 /// ::= 'x86_thiscallcc'
1021 /// ::= 'arm_apcscc'
1022 /// ::= 'arm_aapcscc'
1023 /// ::= 'arm_aapcs_vfpcc'
1024 /// ::= 'msp430_intrcc'
1025 /// ::= 'ptx_kernel'
1026 /// ::= 'ptx_device'
1027 /// ::= 'cc' UINT
1028 ///
ParseOptionalCallingConv(CallingConv::ID & CC)1029 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1030 switch (Lex.getKind()) {
1031 default: CC = CallingConv::C; return false;
1032 case lltok::kw_ccc: CC = CallingConv::C; break;
1033 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1034 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1035 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1036 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1037 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1038 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1039 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1040 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1041 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1042 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1043 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1044 case lltok::kw_cc: {
1045 unsigned ArbitraryCC;
1046 Lex.Lex();
1047 if (ParseUInt32(ArbitraryCC)) {
1048 return true;
1049 } else
1050 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1051 return false;
1052 }
1053 break;
1054 }
1055
1056 Lex.Lex();
1057 return false;
1058 }
1059
1060 /// ParseInstructionMetadata
1061 /// ::= !dbg !42 (',' !dbg !57)*
ParseInstructionMetadata(Instruction * Inst,PerFunctionState * PFS)1062 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1063 PerFunctionState *PFS) {
1064 do {
1065 if (Lex.getKind() != lltok::MetadataVar)
1066 return TokError("expected metadata after comma");
1067
1068 std::string Name = Lex.getStrVal();
1069 unsigned MDK = M->getMDKindID(Name.c_str());
1070 Lex.Lex();
1071
1072 MDNode *Node;
1073 SMLoc Loc = Lex.getLoc();
1074
1075 if (ParseToken(lltok::exclaim, "expected '!' here"))
1076 return true;
1077
1078 // This code is similar to that of ParseMetadataValue, however it needs to
1079 // have special-case code for a forward reference; see the comments on
1080 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1081 // at the top level here.
1082 if (Lex.getKind() == lltok::lbrace) {
1083 ValID ID;
1084 if (ParseMetadataListValue(ID, PFS))
1085 return true;
1086 assert(ID.Kind == ValID::t_MDNode);
1087 Inst->setMetadata(MDK, ID.MDNodeVal);
1088 } else {
1089 unsigned NodeID = 0;
1090 if (ParseMDNodeID(Node, NodeID))
1091 return true;
1092 if (Node) {
1093 // If we got the node, add it to the instruction.
1094 Inst->setMetadata(MDK, Node);
1095 } else {
1096 MDRef R = { Loc, MDK, NodeID };
1097 // Otherwise, remember that this should be resolved later.
1098 ForwardRefInstMetadata[Inst].push_back(R);
1099 }
1100 }
1101
1102 // If this is the end of the list, we're done.
1103 } while (EatIfPresent(lltok::comma));
1104 return false;
1105 }
1106
1107 /// ParseOptionalAlignment
1108 /// ::= /* empty */
1109 /// ::= 'align' 4
ParseOptionalAlignment(unsigned & Alignment)1110 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1111 Alignment = 0;
1112 if (!EatIfPresent(lltok::kw_align))
1113 return false;
1114 LocTy AlignLoc = Lex.getLoc();
1115 if (ParseUInt32(Alignment)) return true;
1116 if (!isPowerOf2_32(Alignment))
1117 return Error(AlignLoc, "alignment is not a power of two");
1118 if (Alignment > Value::MaximumAlignment)
1119 return Error(AlignLoc, "huge alignments are not supported yet");
1120 return false;
1121 }
1122
1123 /// ParseOptionalCommaAlign
1124 /// ::=
1125 /// ::= ',' align 4
1126 ///
1127 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1128 /// end.
ParseOptionalCommaAlign(unsigned & Alignment,bool & AteExtraComma)1129 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1130 bool &AteExtraComma) {
1131 AteExtraComma = false;
1132 while (EatIfPresent(lltok::comma)) {
1133 // Metadata at the end is an early exit.
1134 if (Lex.getKind() == lltok::MetadataVar) {
1135 AteExtraComma = true;
1136 return false;
1137 }
1138
1139 if (Lex.getKind() != lltok::kw_align)
1140 return Error(Lex.getLoc(), "expected metadata or 'align'");
1141
1142 if (ParseOptionalAlignment(Alignment)) return true;
1143 }
1144
1145 return false;
1146 }
1147
1148 /// ParseOptionalStackAlignment
1149 /// ::= /* empty */
1150 /// ::= 'alignstack' '(' 4 ')'
ParseOptionalStackAlignment(unsigned & Alignment)1151 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1152 Alignment = 0;
1153 if (!EatIfPresent(lltok::kw_alignstack))
1154 return false;
1155 LocTy ParenLoc = Lex.getLoc();
1156 if (!EatIfPresent(lltok::lparen))
1157 return Error(ParenLoc, "expected '('");
1158 LocTy AlignLoc = Lex.getLoc();
1159 if (ParseUInt32(Alignment)) return true;
1160 ParenLoc = Lex.getLoc();
1161 if (!EatIfPresent(lltok::rparen))
1162 return Error(ParenLoc, "expected ')'");
1163 if (!isPowerOf2_32(Alignment))
1164 return Error(AlignLoc, "stack alignment is not a power of two");
1165 return false;
1166 }
1167
1168 /// ParseIndexList - This parses the index list for an insert/extractvalue
1169 /// instruction. This sets AteExtraComma in the case where we eat an extra
1170 /// comma at the end of the line and find that it is followed by metadata.
1171 /// Clients that don't allow metadata can call the version of this function that
1172 /// only takes one argument.
1173 ///
1174 /// ParseIndexList
1175 /// ::= (',' uint32)+
1176 ///
ParseIndexList(SmallVectorImpl<unsigned> & Indices,bool & AteExtraComma)1177 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1178 bool &AteExtraComma) {
1179 AteExtraComma = false;
1180
1181 if (Lex.getKind() != lltok::comma)
1182 return TokError("expected ',' as start of index list");
1183
1184 while (EatIfPresent(lltok::comma)) {
1185 if (Lex.getKind() == lltok::MetadataVar) {
1186 AteExtraComma = true;
1187 return false;
1188 }
1189 unsigned Idx = 0;
1190 if (ParseUInt32(Idx)) return true;
1191 Indices.push_back(Idx);
1192 }
1193
1194 return false;
1195 }
1196
1197 //===----------------------------------------------------------------------===//
1198 // Type Parsing.
1199 //===----------------------------------------------------------------------===//
1200
1201 /// ParseType - Parse a type.
ParseType(Type * & Result,bool AllowVoid)1202 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1203 SMLoc TypeLoc = Lex.getLoc();
1204 switch (Lex.getKind()) {
1205 default:
1206 return TokError("expected type");
1207 case lltok::Type:
1208 // Type ::= 'float' | 'void' (etc)
1209 Result = Lex.getTyVal();
1210 Lex.Lex();
1211 break;
1212 case lltok::lbrace:
1213 // Type ::= StructType
1214 if (ParseAnonStructType(Result, false))
1215 return true;
1216 break;
1217 case lltok::lsquare:
1218 // Type ::= '[' ... ']'
1219 Lex.Lex(); // eat the lsquare.
1220 if (ParseArrayVectorType(Result, false))
1221 return true;
1222 break;
1223 case lltok::less: // Either vector or packed struct.
1224 // Type ::= '<' ... '>'
1225 Lex.Lex();
1226 if (Lex.getKind() == lltok::lbrace) {
1227 if (ParseAnonStructType(Result, true) ||
1228 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1229 return true;
1230 } else if (ParseArrayVectorType(Result, true))
1231 return true;
1232 break;
1233 case lltok::LocalVar: {
1234 // Type ::= %foo
1235 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1236
1237 // If the type hasn't been defined yet, create a forward definition and
1238 // remember where that forward def'n was seen (in case it never is defined).
1239 if (Entry.first == 0) {
1240 Entry.first = StructType::createNamed(Context, Lex.getStrVal());
1241 Entry.second = Lex.getLoc();
1242 }
1243 Result = Entry.first;
1244 Lex.Lex();
1245 break;
1246 }
1247
1248 case lltok::LocalVarID: {
1249 // Type ::= %4
1250 if (Lex.getUIntVal() >= NumberedTypes.size())
1251 NumberedTypes.resize(Lex.getUIntVal()+1);
1252 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1253
1254 // If the type hasn't been defined yet, create a forward definition and
1255 // remember where that forward def'n was seen (in case it never is defined).
1256 if (Entry.first == 0) {
1257 Entry.first = StructType::createNamed(Context, "");
1258 Entry.second = Lex.getLoc();
1259 }
1260 Result = Entry.first;
1261 Lex.Lex();
1262 break;
1263 }
1264 }
1265
1266 // Parse the type suffixes.
1267 while (1) {
1268 switch (Lex.getKind()) {
1269 // End of type.
1270 default:
1271 if (!AllowVoid && Result->isVoidTy())
1272 return Error(TypeLoc, "void type only allowed for function results");
1273 return false;
1274
1275 // Type ::= Type '*'
1276 case lltok::star:
1277 if (Result->isLabelTy())
1278 return TokError("basic block pointers are invalid");
1279 if (Result->isVoidTy())
1280 return TokError("pointers to void are invalid - use i8* instead");
1281 if (!PointerType::isValidElementType(Result))
1282 return TokError("pointer to this type is invalid");
1283 Result = PointerType::getUnqual(Result);
1284 Lex.Lex();
1285 break;
1286
1287 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1288 case lltok::kw_addrspace: {
1289 if (Result->isLabelTy())
1290 return TokError("basic block pointers are invalid");
1291 if (Result->isVoidTy())
1292 return TokError("pointers to void are invalid; use i8* instead");
1293 if (!PointerType::isValidElementType(Result))
1294 return TokError("pointer to this type is invalid");
1295 unsigned AddrSpace;
1296 if (ParseOptionalAddrSpace(AddrSpace) ||
1297 ParseToken(lltok::star, "expected '*' in address space"))
1298 return true;
1299
1300 Result = PointerType::get(Result, AddrSpace);
1301 break;
1302 }
1303
1304 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1305 case lltok::lparen:
1306 if (ParseFunctionType(Result))
1307 return true;
1308 break;
1309 }
1310 }
1311 }
1312
1313 /// ParseParameterList
1314 /// ::= '(' ')'
1315 /// ::= '(' Arg (',' Arg)* ')'
1316 /// Arg
1317 /// ::= Type OptionalAttributes Value OptionalAttributes
ParseParameterList(SmallVectorImpl<ParamInfo> & ArgList,PerFunctionState & PFS)1318 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1319 PerFunctionState &PFS) {
1320 if (ParseToken(lltok::lparen, "expected '(' in call"))
1321 return true;
1322
1323 while (Lex.getKind() != lltok::rparen) {
1324 // If this isn't the first argument, we need a comma.
1325 if (!ArgList.empty() &&
1326 ParseToken(lltok::comma, "expected ',' in argument list"))
1327 return true;
1328
1329 // Parse the argument.
1330 LocTy ArgLoc;
1331 Type *ArgTy = 0;
1332 unsigned ArgAttrs1 = Attribute::None;
1333 unsigned ArgAttrs2 = Attribute::None;
1334 Value *V;
1335 if (ParseType(ArgTy, ArgLoc))
1336 return true;
1337
1338 // Otherwise, handle normal operands.
1339 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1340 return true;
1341 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1342 }
1343
1344 Lex.Lex(); // Lex the ')'.
1345 return false;
1346 }
1347
1348
1349
1350 /// ParseArgumentList - Parse the argument list for a function type or function
1351 /// prototype.
1352 /// ::= '(' ArgTypeListI ')'
1353 /// ArgTypeListI
1354 /// ::= /*empty*/
1355 /// ::= '...'
1356 /// ::= ArgTypeList ',' '...'
1357 /// ::= ArgType (',' ArgType)*
1358 ///
ParseArgumentList(SmallVectorImpl<ArgInfo> & ArgList,bool & isVarArg)1359 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1360 bool &isVarArg){
1361 isVarArg = false;
1362 assert(Lex.getKind() == lltok::lparen);
1363 Lex.Lex(); // eat the (.
1364
1365 if (Lex.getKind() == lltok::rparen) {
1366 // empty
1367 } else if (Lex.getKind() == lltok::dotdotdot) {
1368 isVarArg = true;
1369 Lex.Lex();
1370 } else {
1371 LocTy TypeLoc = Lex.getLoc();
1372 Type *ArgTy = 0;
1373 unsigned Attrs;
1374 std::string Name;
1375
1376 if (ParseType(ArgTy) ||
1377 ParseOptionalAttrs(Attrs, 0)) return true;
1378
1379 if (ArgTy->isVoidTy())
1380 return Error(TypeLoc, "argument can not have void type");
1381
1382 if (Lex.getKind() == lltok::LocalVar) {
1383 Name = Lex.getStrVal();
1384 Lex.Lex();
1385 }
1386
1387 if (!FunctionType::isValidArgumentType(ArgTy))
1388 return Error(TypeLoc, "invalid type for function argument");
1389
1390 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1391
1392 while (EatIfPresent(lltok::comma)) {
1393 // Handle ... at end of arg list.
1394 if (EatIfPresent(lltok::dotdotdot)) {
1395 isVarArg = true;
1396 break;
1397 }
1398
1399 // Otherwise must be an argument type.
1400 TypeLoc = Lex.getLoc();
1401 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1402
1403 if (ArgTy->isVoidTy())
1404 return Error(TypeLoc, "argument can not have void type");
1405
1406 if (Lex.getKind() == lltok::LocalVar) {
1407 Name = Lex.getStrVal();
1408 Lex.Lex();
1409 } else {
1410 Name = "";
1411 }
1412
1413 if (!ArgTy->isFirstClassType())
1414 return Error(TypeLoc, "invalid type for function argument");
1415
1416 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1417 }
1418 }
1419
1420 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1421 }
1422
1423 /// ParseFunctionType
1424 /// ::= Type ArgumentList OptionalAttrs
ParseFunctionType(Type * & Result)1425 bool LLParser::ParseFunctionType(Type *&Result) {
1426 assert(Lex.getKind() == lltok::lparen);
1427
1428 if (!FunctionType::isValidReturnType(Result))
1429 return TokError("invalid function return type");
1430
1431 SmallVector<ArgInfo, 8> ArgList;
1432 bool isVarArg;
1433 if (ParseArgumentList(ArgList, isVarArg))
1434 return true;
1435
1436 // Reject names on the arguments lists.
1437 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1438 if (!ArgList[i].Name.empty())
1439 return Error(ArgList[i].Loc, "argument name invalid in function type");
1440 if (ArgList[i].Attrs != 0)
1441 return Error(ArgList[i].Loc,
1442 "argument attributes invalid in function type");
1443 }
1444
1445 SmallVector<Type*, 16> ArgListTy;
1446 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1447 ArgListTy.push_back(ArgList[i].Ty);
1448
1449 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1450 return false;
1451 }
1452
1453 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1454 /// other structs.
ParseAnonStructType(Type * & Result,bool Packed)1455 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1456 SmallVector<Type*, 8> Elts;
1457 if (ParseStructBody(Elts)) return true;
1458
1459 Result = StructType::get(Context, Elts, Packed);
1460 return false;
1461 }
1462
1463 /// ParseStructDefinition - Parse a struct in a 'type' definition.
ParseStructDefinition(SMLoc TypeLoc,StringRef Name,std::pair<Type *,LocTy> & Entry,Type * & ResultTy)1464 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1465 std::pair<Type*, LocTy> &Entry,
1466 Type *&ResultTy) {
1467 // If the type was already defined, diagnose the redefinition.
1468 if (Entry.first && !Entry.second.isValid())
1469 return Error(TypeLoc, "redefinition of type");
1470
1471 // If we have opaque, just return without filling in the definition for the
1472 // struct. This counts as a definition as far as the .ll file goes.
1473 if (EatIfPresent(lltok::kw_opaque)) {
1474 // This type is being defined, so clear the location to indicate this.
1475 Entry.second = SMLoc();
1476
1477 // If this type number has never been uttered, create it.
1478 if (Entry.first == 0)
1479 Entry.first = StructType::createNamed(Context, Name);
1480 ResultTy = Entry.first;
1481 return false;
1482 }
1483
1484 // If the type starts with '<', then it is either a packed struct or a vector.
1485 bool isPacked = EatIfPresent(lltok::less);
1486
1487 // If we don't have a struct, then we have a random type alias, which we
1488 // accept for compatibility with old files. These types are not allowed to be
1489 // forward referenced and not allowed to be recursive.
1490 if (Lex.getKind() != lltok::lbrace) {
1491 if (Entry.first)
1492 return Error(TypeLoc, "forward references to non-struct type");
1493
1494 ResultTy = 0;
1495 if (isPacked)
1496 return ParseArrayVectorType(ResultTy, true);
1497 return ParseType(ResultTy);
1498 }
1499
1500 // This type is being defined, so clear the location to indicate this.
1501 Entry.second = SMLoc();
1502
1503 // If this type number has never been uttered, create it.
1504 if (Entry.first == 0)
1505 Entry.first = StructType::createNamed(Context, Name);
1506
1507 StructType *STy = cast<StructType>(Entry.first);
1508
1509 SmallVector<Type*, 8> Body;
1510 if (ParseStructBody(Body) ||
1511 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1512 return true;
1513
1514 STy->setBody(Body, isPacked);
1515 ResultTy = STy;
1516 return false;
1517 }
1518
1519
1520 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1521 /// StructType
1522 /// ::= '{' '}'
1523 /// ::= '{' Type (',' Type)* '}'
1524 /// ::= '<' '{' '}' '>'
1525 /// ::= '<' '{' Type (',' Type)* '}' '>'
ParseStructBody(SmallVectorImpl<Type * > & Body)1526 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1527 assert(Lex.getKind() == lltok::lbrace);
1528 Lex.Lex(); // Consume the '{'
1529
1530 // Handle the empty struct.
1531 if (EatIfPresent(lltok::rbrace))
1532 return false;
1533
1534 LocTy EltTyLoc = Lex.getLoc();
1535 Type *Ty = 0;
1536 if (ParseType(Ty)) return true;
1537 Body.push_back(Ty);
1538
1539 if (!StructType::isValidElementType(Ty))
1540 return Error(EltTyLoc, "invalid element type for struct");
1541
1542 while (EatIfPresent(lltok::comma)) {
1543 EltTyLoc = Lex.getLoc();
1544 if (ParseType(Ty)) return true;
1545
1546 if (!StructType::isValidElementType(Ty))
1547 return Error(EltTyLoc, "invalid element type for struct");
1548
1549 Body.push_back(Ty);
1550 }
1551
1552 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1553 }
1554
1555 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1556 /// token has already been consumed.
1557 /// Type
1558 /// ::= '[' APSINTVAL 'x' Types ']'
1559 /// ::= '<' APSINTVAL 'x' Types '>'
ParseArrayVectorType(Type * & Result,bool isVector)1560 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1561 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1562 Lex.getAPSIntVal().getBitWidth() > 64)
1563 return TokError("expected number in address space");
1564
1565 LocTy SizeLoc = Lex.getLoc();
1566 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1567 Lex.Lex();
1568
1569 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1570 return true;
1571
1572 LocTy TypeLoc = Lex.getLoc();
1573 Type *EltTy = 0;
1574 if (ParseType(EltTy)) return true;
1575
1576 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1577 "expected end of sequential type"))
1578 return true;
1579
1580 if (isVector) {
1581 if (Size == 0)
1582 return Error(SizeLoc, "zero element vector is illegal");
1583 if ((unsigned)Size != Size)
1584 return Error(SizeLoc, "size too large for vector");
1585 if (!VectorType::isValidElementType(EltTy))
1586 return Error(TypeLoc, "vector element type must be fp or integer");
1587 Result = VectorType::get(EltTy, unsigned(Size));
1588 } else {
1589 if (!ArrayType::isValidElementType(EltTy))
1590 return Error(TypeLoc, "invalid array element type");
1591 Result = ArrayType::get(EltTy, Size);
1592 }
1593 return false;
1594 }
1595
1596 //===----------------------------------------------------------------------===//
1597 // Function Semantic Analysis.
1598 //===----------------------------------------------------------------------===//
1599
PerFunctionState(LLParser & p,Function & f,int functionNumber)1600 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1601 int functionNumber)
1602 : P(p), F(f), FunctionNumber(functionNumber) {
1603
1604 // Insert unnamed arguments into the NumberedVals list.
1605 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1606 AI != E; ++AI)
1607 if (!AI->hasName())
1608 NumberedVals.push_back(AI);
1609 }
1610
~PerFunctionState()1611 LLParser::PerFunctionState::~PerFunctionState() {
1612 // If there were any forward referenced non-basicblock values, delete them.
1613 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1614 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1615 if (!isa<BasicBlock>(I->second.first)) {
1616 I->second.first->replaceAllUsesWith(
1617 UndefValue::get(I->second.first->getType()));
1618 delete I->second.first;
1619 I->second.first = 0;
1620 }
1621
1622 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1623 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1624 if (!isa<BasicBlock>(I->second.first)) {
1625 I->second.first->replaceAllUsesWith(
1626 UndefValue::get(I->second.first->getType()));
1627 delete I->second.first;
1628 I->second.first = 0;
1629 }
1630 }
1631
FinishFunction()1632 bool LLParser::PerFunctionState::FinishFunction() {
1633 // Check to see if someone took the address of labels in this block.
1634 if (!P.ForwardRefBlockAddresses.empty()) {
1635 ValID FunctionID;
1636 if (!F.getName().empty()) {
1637 FunctionID.Kind = ValID::t_GlobalName;
1638 FunctionID.StrVal = F.getName();
1639 } else {
1640 FunctionID.Kind = ValID::t_GlobalID;
1641 FunctionID.UIntVal = FunctionNumber;
1642 }
1643
1644 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1645 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1646 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1647 // Resolve all these references.
1648 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1649 return true;
1650
1651 P.ForwardRefBlockAddresses.erase(FRBAI);
1652 }
1653 }
1654
1655 if (!ForwardRefVals.empty())
1656 return P.Error(ForwardRefVals.begin()->second.second,
1657 "use of undefined value '%" + ForwardRefVals.begin()->first +
1658 "'");
1659 if (!ForwardRefValIDs.empty())
1660 return P.Error(ForwardRefValIDs.begin()->second.second,
1661 "use of undefined value '%" +
1662 Twine(ForwardRefValIDs.begin()->first) + "'");
1663 return false;
1664 }
1665
1666
1667 /// GetVal - Get a value with the specified name or ID, creating a
1668 /// forward reference record if needed. This can return null if the value
1669 /// exists but does not have the right type.
GetVal(const std::string & Name,Type * Ty,LocTy Loc)1670 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1671 Type *Ty, LocTy Loc) {
1672 // Look this name up in the normal function symbol table.
1673 Value *Val = F.getValueSymbolTable().lookup(Name);
1674
1675 // If this is a forward reference for the value, see if we already created a
1676 // forward ref record.
1677 if (Val == 0) {
1678 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1679 I = ForwardRefVals.find(Name);
1680 if (I != ForwardRefVals.end())
1681 Val = I->second.first;
1682 }
1683
1684 // If we have the value in the symbol table or fwd-ref table, return it.
1685 if (Val) {
1686 if (Val->getType() == Ty) return Val;
1687 if (Ty->isLabelTy())
1688 P.Error(Loc, "'%" + Name + "' is not a basic block");
1689 else
1690 P.Error(Loc, "'%" + Name + "' defined with type '" +
1691 getTypeString(Val->getType()) + "'");
1692 return 0;
1693 }
1694
1695 // Don't make placeholders with invalid type.
1696 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1697 P.Error(Loc, "invalid use of a non-first-class type");
1698 return 0;
1699 }
1700
1701 // Otherwise, create a new forward reference for this value and remember it.
1702 Value *FwdVal;
1703 if (Ty->isLabelTy())
1704 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1705 else
1706 FwdVal = new Argument(Ty, Name);
1707
1708 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1709 return FwdVal;
1710 }
1711
GetVal(unsigned ID,Type * Ty,LocTy Loc)1712 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1713 LocTy Loc) {
1714 // Look this name up in the normal function symbol table.
1715 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1716
1717 // If this is a forward reference for the value, see if we already created a
1718 // forward ref record.
1719 if (Val == 0) {
1720 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1721 I = ForwardRefValIDs.find(ID);
1722 if (I != ForwardRefValIDs.end())
1723 Val = I->second.first;
1724 }
1725
1726 // If we have the value in the symbol table or fwd-ref table, return it.
1727 if (Val) {
1728 if (Val->getType() == Ty) return Val;
1729 if (Ty->isLabelTy())
1730 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1731 else
1732 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1733 getTypeString(Val->getType()) + "'");
1734 return 0;
1735 }
1736
1737 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1738 P.Error(Loc, "invalid use of a non-first-class type");
1739 return 0;
1740 }
1741
1742 // Otherwise, create a new forward reference for this value and remember it.
1743 Value *FwdVal;
1744 if (Ty->isLabelTy())
1745 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1746 else
1747 FwdVal = new Argument(Ty);
1748
1749 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1750 return FwdVal;
1751 }
1752
1753 /// SetInstName - After an instruction is parsed and inserted into its
1754 /// basic block, this installs its name.
SetInstName(int NameID,const std::string & NameStr,LocTy NameLoc,Instruction * Inst)1755 bool LLParser::PerFunctionState::SetInstName(int NameID,
1756 const std::string &NameStr,
1757 LocTy NameLoc, Instruction *Inst) {
1758 // If this instruction has void type, it cannot have a name or ID specified.
1759 if (Inst->getType()->isVoidTy()) {
1760 if (NameID != -1 || !NameStr.empty())
1761 return P.Error(NameLoc, "instructions returning void cannot have a name");
1762 return false;
1763 }
1764
1765 // If this was a numbered instruction, verify that the instruction is the
1766 // expected value and resolve any forward references.
1767 if (NameStr.empty()) {
1768 // If neither a name nor an ID was specified, just use the next ID.
1769 if (NameID == -1)
1770 NameID = NumberedVals.size();
1771
1772 if (unsigned(NameID) != NumberedVals.size())
1773 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1774 Twine(NumberedVals.size()) + "'");
1775
1776 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1777 ForwardRefValIDs.find(NameID);
1778 if (FI != ForwardRefValIDs.end()) {
1779 if (FI->second.first->getType() != Inst->getType())
1780 return P.Error(NameLoc, "instruction forward referenced with type '" +
1781 getTypeString(FI->second.first->getType()) + "'");
1782 FI->second.first->replaceAllUsesWith(Inst);
1783 delete FI->second.first;
1784 ForwardRefValIDs.erase(FI);
1785 }
1786
1787 NumberedVals.push_back(Inst);
1788 return false;
1789 }
1790
1791 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1792 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1793 FI = ForwardRefVals.find(NameStr);
1794 if (FI != ForwardRefVals.end()) {
1795 if (FI->second.first->getType() != Inst->getType())
1796 return P.Error(NameLoc, "instruction forward referenced with type '" +
1797 getTypeString(FI->second.first->getType()) + "'");
1798 FI->second.first->replaceAllUsesWith(Inst);
1799 delete FI->second.first;
1800 ForwardRefVals.erase(FI);
1801 }
1802
1803 // Set the name on the instruction.
1804 Inst->setName(NameStr);
1805
1806 if (Inst->getName() != NameStr)
1807 return P.Error(NameLoc, "multiple definition of local value named '" +
1808 NameStr + "'");
1809 return false;
1810 }
1811
1812 /// GetBB - Get a basic block with the specified name or ID, creating a
1813 /// forward reference record if needed.
GetBB(const std::string & Name,LocTy Loc)1814 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1815 LocTy Loc) {
1816 return cast_or_null<BasicBlock>(GetVal(Name,
1817 Type::getLabelTy(F.getContext()), Loc));
1818 }
1819
GetBB(unsigned ID,LocTy Loc)1820 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1821 return cast_or_null<BasicBlock>(GetVal(ID,
1822 Type::getLabelTy(F.getContext()), Loc));
1823 }
1824
1825 /// DefineBB - Define the specified basic block, which is either named or
1826 /// unnamed. If there is an error, this returns null otherwise it returns
1827 /// the block being defined.
DefineBB(const std::string & Name,LocTy Loc)1828 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1829 LocTy Loc) {
1830 BasicBlock *BB;
1831 if (Name.empty())
1832 BB = GetBB(NumberedVals.size(), Loc);
1833 else
1834 BB = GetBB(Name, Loc);
1835 if (BB == 0) return 0; // Already diagnosed error.
1836
1837 // Move the block to the end of the function. Forward ref'd blocks are
1838 // inserted wherever they happen to be referenced.
1839 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1840
1841 // Remove the block from forward ref sets.
1842 if (Name.empty()) {
1843 ForwardRefValIDs.erase(NumberedVals.size());
1844 NumberedVals.push_back(BB);
1845 } else {
1846 // BB forward references are already in the function symbol table.
1847 ForwardRefVals.erase(Name);
1848 }
1849
1850 return BB;
1851 }
1852
1853 //===----------------------------------------------------------------------===//
1854 // Constants.
1855 //===----------------------------------------------------------------------===//
1856
1857 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1858 /// type implied. For example, if we parse "4" we don't know what integer type
1859 /// it has. The value will later be combined with its type and checked for
1860 /// sanity. PFS is used to convert function-local operands of metadata (since
1861 /// metadata operands are not just parsed here but also converted to values).
1862 /// PFS can be null when we are not parsing metadata values inside a function.
ParseValID(ValID & ID,PerFunctionState * PFS)1863 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1864 ID.Loc = Lex.getLoc();
1865 switch (Lex.getKind()) {
1866 default: return TokError("expected value token");
1867 case lltok::GlobalID: // @42
1868 ID.UIntVal = Lex.getUIntVal();
1869 ID.Kind = ValID::t_GlobalID;
1870 break;
1871 case lltok::GlobalVar: // @foo
1872 ID.StrVal = Lex.getStrVal();
1873 ID.Kind = ValID::t_GlobalName;
1874 break;
1875 case lltok::LocalVarID: // %42
1876 ID.UIntVal = Lex.getUIntVal();
1877 ID.Kind = ValID::t_LocalID;
1878 break;
1879 case lltok::LocalVar: // %foo
1880 ID.StrVal = Lex.getStrVal();
1881 ID.Kind = ValID::t_LocalName;
1882 break;
1883 case lltok::exclaim: // !42, !{...}, or !"foo"
1884 return ParseMetadataValue(ID, PFS);
1885 case lltok::APSInt:
1886 ID.APSIntVal = Lex.getAPSIntVal();
1887 ID.Kind = ValID::t_APSInt;
1888 break;
1889 case lltok::APFloat:
1890 ID.APFloatVal = Lex.getAPFloatVal();
1891 ID.Kind = ValID::t_APFloat;
1892 break;
1893 case lltok::kw_true:
1894 ID.ConstantVal = ConstantInt::getTrue(Context);
1895 ID.Kind = ValID::t_Constant;
1896 break;
1897 case lltok::kw_false:
1898 ID.ConstantVal = ConstantInt::getFalse(Context);
1899 ID.Kind = ValID::t_Constant;
1900 break;
1901 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1902 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1903 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1904
1905 case lltok::lbrace: {
1906 // ValID ::= '{' ConstVector '}'
1907 Lex.Lex();
1908 SmallVector<Constant*, 16> Elts;
1909 if (ParseGlobalValueVector(Elts) ||
1910 ParseToken(lltok::rbrace, "expected end of struct constant"))
1911 return true;
1912
1913 ID.ConstantStructElts = new Constant*[Elts.size()];
1914 ID.UIntVal = Elts.size();
1915 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1916 ID.Kind = ValID::t_ConstantStruct;
1917 return false;
1918 }
1919 case lltok::less: {
1920 // ValID ::= '<' ConstVector '>' --> Vector.
1921 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1922 Lex.Lex();
1923 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1924
1925 SmallVector<Constant*, 16> Elts;
1926 LocTy FirstEltLoc = Lex.getLoc();
1927 if (ParseGlobalValueVector(Elts) ||
1928 (isPackedStruct &&
1929 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1930 ParseToken(lltok::greater, "expected end of constant"))
1931 return true;
1932
1933 if (isPackedStruct) {
1934 ID.ConstantStructElts = new Constant*[Elts.size()];
1935 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1936 ID.UIntVal = Elts.size();
1937 ID.Kind = ValID::t_PackedConstantStruct;
1938 return false;
1939 }
1940
1941 if (Elts.empty())
1942 return Error(ID.Loc, "constant vector must not be empty");
1943
1944 if (!Elts[0]->getType()->isIntegerTy() &&
1945 !Elts[0]->getType()->isFloatingPointTy())
1946 return Error(FirstEltLoc,
1947 "vector elements must have integer or floating point type");
1948
1949 // Verify that all the vector elements have the same type.
1950 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1951 if (Elts[i]->getType() != Elts[0]->getType())
1952 return Error(FirstEltLoc,
1953 "vector element #" + Twine(i) +
1954 " is not of type '" + getTypeString(Elts[0]->getType()));
1955
1956 ID.ConstantVal = ConstantVector::get(Elts);
1957 ID.Kind = ValID::t_Constant;
1958 return false;
1959 }
1960 case lltok::lsquare: { // Array Constant
1961 Lex.Lex();
1962 SmallVector<Constant*, 16> Elts;
1963 LocTy FirstEltLoc = Lex.getLoc();
1964 if (ParseGlobalValueVector(Elts) ||
1965 ParseToken(lltok::rsquare, "expected end of array constant"))
1966 return true;
1967
1968 // Handle empty element.
1969 if (Elts.empty()) {
1970 // Use undef instead of an array because it's inconvenient to determine
1971 // the element type at this point, there being no elements to examine.
1972 ID.Kind = ValID::t_EmptyArray;
1973 return false;
1974 }
1975
1976 if (!Elts[0]->getType()->isFirstClassType())
1977 return Error(FirstEltLoc, "invalid array element type: " +
1978 getTypeString(Elts[0]->getType()));
1979
1980 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1981
1982 // Verify all elements are correct type!
1983 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1984 if (Elts[i]->getType() != Elts[0]->getType())
1985 return Error(FirstEltLoc,
1986 "array element #" + Twine(i) +
1987 " is not of type '" + getTypeString(Elts[0]->getType()));
1988 }
1989
1990 ID.ConstantVal = ConstantArray::get(ATy, Elts);
1991 ID.Kind = ValID::t_Constant;
1992 return false;
1993 }
1994 case lltok::kw_c: // c "foo"
1995 Lex.Lex();
1996 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
1997 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1998 ID.Kind = ValID::t_Constant;
1999 return false;
2000
2001 case lltok::kw_asm: {
2002 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2003 bool HasSideEffect, AlignStack;
2004 Lex.Lex();
2005 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2006 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2007 ParseStringConstant(ID.StrVal) ||
2008 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2009 ParseToken(lltok::StringConstant, "expected constraint string"))
2010 return true;
2011 ID.StrVal2 = Lex.getStrVal();
2012 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2013 ID.Kind = ValID::t_InlineAsm;
2014 return false;
2015 }
2016
2017 case lltok::kw_blockaddress: {
2018 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2019 Lex.Lex();
2020
2021 ValID Fn, Label;
2022 LocTy FnLoc, LabelLoc;
2023
2024 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2025 ParseValID(Fn) ||
2026 ParseToken(lltok::comma, "expected comma in block address expression")||
2027 ParseValID(Label) ||
2028 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2029 return true;
2030
2031 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2032 return Error(Fn.Loc, "expected function name in blockaddress");
2033 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2034 return Error(Label.Loc, "expected basic block name in blockaddress");
2035
2036 // Make a global variable as a placeholder for this reference.
2037 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2038 false, GlobalValue::InternalLinkage,
2039 0, "");
2040 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2041 ID.ConstantVal = FwdRef;
2042 ID.Kind = ValID::t_Constant;
2043 return false;
2044 }
2045
2046 case lltok::kw_trunc:
2047 case lltok::kw_zext:
2048 case lltok::kw_sext:
2049 case lltok::kw_fptrunc:
2050 case lltok::kw_fpext:
2051 case lltok::kw_bitcast:
2052 case lltok::kw_uitofp:
2053 case lltok::kw_sitofp:
2054 case lltok::kw_fptoui:
2055 case lltok::kw_fptosi:
2056 case lltok::kw_inttoptr:
2057 case lltok::kw_ptrtoint: {
2058 unsigned Opc = Lex.getUIntVal();
2059 Type *DestTy = 0;
2060 Constant *SrcVal;
2061 Lex.Lex();
2062 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2063 ParseGlobalTypeAndValue(SrcVal) ||
2064 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2065 ParseType(DestTy) ||
2066 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2067 return true;
2068 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2069 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2070 getTypeString(SrcVal->getType()) + "' to '" +
2071 getTypeString(DestTy) + "'");
2072 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2073 SrcVal, DestTy);
2074 ID.Kind = ValID::t_Constant;
2075 return false;
2076 }
2077 case lltok::kw_extractvalue: {
2078 Lex.Lex();
2079 Constant *Val;
2080 SmallVector<unsigned, 4> Indices;
2081 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2082 ParseGlobalTypeAndValue(Val) ||
2083 ParseIndexList(Indices) ||
2084 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2085 return true;
2086
2087 if (!Val->getType()->isAggregateType())
2088 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2089 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2090 return Error(ID.Loc, "invalid indices for extractvalue");
2091 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2092 ID.Kind = ValID::t_Constant;
2093 return false;
2094 }
2095 case lltok::kw_insertvalue: {
2096 Lex.Lex();
2097 Constant *Val0, *Val1;
2098 SmallVector<unsigned, 4> Indices;
2099 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2100 ParseGlobalTypeAndValue(Val0) ||
2101 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2102 ParseGlobalTypeAndValue(Val1) ||
2103 ParseIndexList(Indices) ||
2104 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2105 return true;
2106 if (!Val0->getType()->isAggregateType())
2107 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2108 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2109 return Error(ID.Loc, "invalid indices for insertvalue");
2110 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2111 ID.Kind = ValID::t_Constant;
2112 return false;
2113 }
2114 case lltok::kw_icmp:
2115 case lltok::kw_fcmp: {
2116 unsigned PredVal, Opc = Lex.getUIntVal();
2117 Constant *Val0, *Val1;
2118 Lex.Lex();
2119 if (ParseCmpPredicate(PredVal, Opc) ||
2120 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2121 ParseGlobalTypeAndValue(Val0) ||
2122 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2123 ParseGlobalTypeAndValue(Val1) ||
2124 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2125 return true;
2126
2127 if (Val0->getType() != Val1->getType())
2128 return Error(ID.Loc, "compare operands must have the same type");
2129
2130 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2131
2132 if (Opc == Instruction::FCmp) {
2133 if (!Val0->getType()->isFPOrFPVectorTy())
2134 return Error(ID.Loc, "fcmp requires floating point operands");
2135 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2136 } else {
2137 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2138 if (!Val0->getType()->isIntOrIntVectorTy() &&
2139 !Val0->getType()->isPointerTy())
2140 return Error(ID.Loc, "icmp requires pointer or integer operands");
2141 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2142 }
2143 ID.Kind = ValID::t_Constant;
2144 return false;
2145 }
2146
2147 // Binary Operators.
2148 case lltok::kw_add:
2149 case lltok::kw_fadd:
2150 case lltok::kw_sub:
2151 case lltok::kw_fsub:
2152 case lltok::kw_mul:
2153 case lltok::kw_fmul:
2154 case lltok::kw_udiv:
2155 case lltok::kw_sdiv:
2156 case lltok::kw_fdiv:
2157 case lltok::kw_urem:
2158 case lltok::kw_srem:
2159 case lltok::kw_frem:
2160 case lltok::kw_shl:
2161 case lltok::kw_lshr:
2162 case lltok::kw_ashr: {
2163 bool NUW = false;
2164 bool NSW = false;
2165 bool Exact = false;
2166 unsigned Opc = Lex.getUIntVal();
2167 Constant *Val0, *Val1;
2168 Lex.Lex();
2169 LocTy ModifierLoc = Lex.getLoc();
2170 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2171 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2172 if (EatIfPresent(lltok::kw_nuw))
2173 NUW = true;
2174 if (EatIfPresent(lltok::kw_nsw)) {
2175 NSW = true;
2176 if (EatIfPresent(lltok::kw_nuw))
2177 NUW = true;
2178 }
2179 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2180 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2181 if (EatIfPresent(lltok::kw_exact))
2182 Exact = true;
2183 }
2184 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2185 ParseGlobalTypeAndValue(Val0) ||
2186 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2187 ParseGlobalTypeAndValue(Val1) ||
2188 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2189 return true;
2190 if (Val0->getType() != Val1->getType())
2191 return Error(ID.Loc, "operands of constexpr must have same type");
2192 if (!Val0->getType()->isIntOrIntVectorTy()) {
2193 if (NUW)
2194 return Error(ModifierLoc, "nuw only applies to integer operations");
2195 if (NSW)
2196 return Error(ModifierLoc, "nsw only applies to integer operations");
2197 }
2198 // Check that the type is valid for the operator.
2199 switch (Opc) {
2200 case Instruction::Add:
2201 case Instruction::Sub:
2202 case Instruction::Mul:
2203 case Instruction::UDiv:
2204 case Instruction::SDiv:
2205 case Instruction::URem:
2206 case Instruction::SRem:
2207 case Instruction::Shl:
2208 case Instruction::AShr:
2209 case Instruction::LShr:
2210 if (!Val0->getType()->isIntOrIntVectorTy())
2211 return Error(ID.Loc, "constexpr requires integer operands");
2212 break;
2213 case Instruction::FAdd:
2214 case Instruction::FSub:
2215 case Instruction::FMul:
2216 case Instruction::FDiv:
2217 case Instruction::FRem:
2218 if (!Val0->getType()->isFPOrFPVectorTy())
2219 return Error(ID.Loc, "constexpr requires fp operands");
2220 break;
2221 default: llvm_unreachable("Unknown binary operator!");
2222 }
2223 unsigned Flags = 0;
2224 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2225 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2226 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2227 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2228 ID.ConstantVal = C;
2229 ID.Kind = ValID::t_Constant;
2230 return false;
2231 }
2232
2233 // Logical Operations
2234 case lltok::kw_and:
2235 case lltok::kw_or:
2236 case lltok::kw_xor: {
2237 unsigned Opc = Lex.getUIntVal();
2238 Constant *Val0, *Val1;
2239 Lex.Lex();
2240 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2241 ParseGlobalTypeAndValue(Val0) ||
2242 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2243 ParseGlobalTypeAndValue(Val1) ||
2244 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2245 return true;
2246 if (Val0->getType() != Val1->getType())
2247 return Error(ID.Loc, "operands of constexpr must have same type");
2248 if (!Val0->getType()->isIntOrIntVectorTy())
2249 return Error(ID.Loc,
2250 "constexpr requires integer or integer vector operands");
2251 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2252 ID.Kind = ValID::t_Constant;
2253 return false;
2254 }
2255
2256 case lltok::kw_getelementptr:
2257 case lltok::kw_shufflevector:
2258 case lltok::kw_insertelement:
2259 case lltok::kw_extractelement:
2260 case lltok::kw_select: {
2261 unsigned Opc = Lex.getUIntVal();
2262 SmallVector<Constant*, 16> Elts;
2263 bool InBounds = false;
2264 Lex.Lex();
2265 if (Opc == Instruction::GetElementPtr)
2266 InBounds = EatIfPresent(lltok::kw_inbounds);
2267 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2268 ParseGlobalValueVector(Elts) ||
2269 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2270 return true;
2271
2272 if (Opc == Instruction::GetElementPtr) {
2273 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2274 return Error(ID.Loc, "getelementptr requires pointer operand");
2275
2276 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2277 (Value**)(Elts.data() + 1),
2278 Elts.size() - 1))
2279 return Error(ID.Loc, "invalid indices for getelementptr");
2280 ID.ConstantVal = InBounds ?
2281 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2282 Elts.data() + 1,
2283 Elts.size() - 1) :
2284 ConstantExpr::getGetElementPtr(Elts[0],
2285 Elts.data() + 1, Elts.size() - 1);
2286 } else if (Opc == Instruction::Select) {
2287 if (Elts.size() != 3)
2288 return Error(ID.Loc, "expected three operands to select");
2289 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2290 Elts[2]))
2291 return Error(ID.Loc, Reason);
2292 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2293 } else if (Opc == Instruction::ShuffleVector) {
2294 if (Elts.size() != 3)
2295 return Error(ID.Loc, "expected three operands to shufflevector");
2296 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2297 return Error(ID.Loc, "invalid operands to shufflevector");
2298 ID.ConstantVal =
2299 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2300 } else if (Opc == Instruction::ExtractElement) {
2301 if (Elts.size() != 2)
2302 return Error(ID.Loc, "expected two operands to extractelement");
2303 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2304 return Error(ID.Loc, "invalid extractelement operands");
2305 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2306 } else {
2307 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2308 if (Elts.size() != 3)
2309 return Error(ID.Loc, "expected three operands to insertelement");
2310 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2311 return Error(ID.Loc, "invalid insertelement operands");
2312 ID.ConstantVal =
2313 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2314 }
2315
2316 ID.Kind = ValID::t_Constant;
2317 return false;
2318 }
2319 }
2320
2321 Lex.Lex();
2322 return false;
2323 }
2324
2325 /// ParseGlobalValue - Parse a global value with the specified type.
ParseGlobalValue(Type * Ty,Constant * & C)2326 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2327 C = 0;
2328 ValID ID;
2329 Value *V = NULL;
2330 bool Parsed = ParseValID(ID) ||
2331 ConvertValIDToValue(Ty, ID, V, NULL);
2332 if (V && !(C = dyn_cast<Constant>(V)))
2333 return Error(ID.Loc, "global values must be constants");
2334 return Parsed;
2335 }
2336
ParseGlobalTypeAndValue(Constant * & V)2337 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2338 Type *Ty = 0;
2339 return ParseType(Ty) ||
2340 ParseGlobalValue(Ty, V);
2341 }
2342
2343 /// ParseGlobalValueVector
2344 /// ::= /*empty*/
2345 /// ::= TypeAndValue (',' TypeAndValue)*
ParseGlobalValueVector(SmallVectorImpl<Constant * > & Elts)2346 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2347 // Empty list.
2348 if (Lex.getKind() == lltok::rbrace ||
2349 Lex.getKind() == lltok::rsquare ||
2350 Lex.getKind() == lltok::greater ||
2351 Lex.getKind() == lltok::rparen)
2352 return false;
2353
2354 Constant *C;
2355 if (ParseGlobalTypeAndValue(C)) return true;
2356 Elts.push_back(C);
2357
2358 while (EatIfPresent(lltok::comma)) {
2359 if (ParseGlobalTypeAndValue(C)) return true;
2360 Elts.push_back(C);
2361 }
2362
2363 return false;
2364 }
2365
ParseMetadataListValue(ValID & ID,PerFunctionState * PFS)2366 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2367 assert(Lex.getKind() == lltok::lbrace);
2368 Lex.Lex();
2369
2370 SmallVector<Value*, 16> Elts;
2371 if (ParseMDNodeVector(Elts, PFS) ||
2372 ParseToken(lltok::rbrace, "expected end of metadata node"))
2373 return true;
2374
2375 ID.MDNodeVal = MDNode::get(Context, Elts);
2376 ID.Kind = ValID::t_MDNode;
2377 return false;
2378 }
2379
2380 /// ParseMetadataValue
2381 /// ::= !42
2382 /// ::= !{...}
2383 /// ::= !"string"
ParseMetadataValue(ValID & ID,PerFunctionState * PFS)2384 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2385 assert(Lex.getKind() == lltok::exclaim);
2386 Lex.Lex();
2387
2388 // MDNode:
2389 // !{ ... }
2390 if (Lex.getKind() == lltok::lbrace)
2391 return ParseMetadataListValue(ID, PFS);
2392
2393 // Standalone metadata reference
2394 // !42
2395 if (Lex.getKind() == lltok::APSInt) {
2396 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2397 ID.Kind = ValID::t_MDNode;
2398 return false;
2399 }
2400
2401 // MDString:
2402 // ::= '!' STRINGCONSTANT
2403 if (ParseMDString(ID.MDStringVal)) return true;
2404 ID.Kind = ValID::t_MDString;
2405 return false;
2406 }
2407
2408
2409 //===----------------------------------------------------------------------===//
2410 // Function Parsing.
2411 //===----------------------------------------------------------------------===//
2412
ConvertValIDToValue(Type * Ty,ValID & ID,Value * & V,PerFunctionState * PFS)2413 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2414 PerFunctionState *PFS) {
2415 if (Ty->isFunctionTy())
2416 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2417
2418 switch (ID.Kind) {
2419 default: llvm_unreachable("Unknown ValID!");
2420 case ValID::t_LocalID:
2421 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2422 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2423 return (V == 0);
2424 case ValID::t_LocalName:
2425 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2426 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2427 return (V == 0);
2428 case ValID::t_InlineAsm: {
2429 PointerType *PTy = dyn_cast<PointerType>(Ty);
2430 FunctionType *FTy =
2431 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2432 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2433 return Error(ID.Loc, "invalid type for inline asm constraint string");
2434 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2435 return false;
2436 }
2437 case ValID::t_MDNode:
2438 if (!Ty->isMetadataTy())
2439 return Error(ID.Loc, "metadata value must have metadata type");
2440 V = ID.MDNodeVal;
2441 return false;
2442 case ValID::t_MDString:
2443 if (!Ty->isMetadataTy())
2444 return Error(ID.Loc, "metadata value must have metadata type");
2445 V = ID.MDStringVal;
2446 return false;
2447 case ValID::t_GlobalName:
2448 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2449 return V == 0;
2450 case ValID::t_GlobalID:
2451 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2452 return V == 0;
2453 case ValID::t_APSInt:
2454 if (!Ty->isIntegerTy())
2455 return Error(ID.Loc, "integer constant must have integer type");
2456 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2457 V = ConstantInt::get(Context, ID.APSIntVal);
2458 return false;
2459 case ValID::t_APFloat:
2460 if (!Ty->isFloatingPointTy() ||
2461 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2462 return Error(ID.Loc, "floating point constant invalid for type");
2463
2464 // The lexer has no type info, so builds all float and double FP constants
2465 // as double. Fix this here. Long double does not need this.
2466 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2467 Ty->isFloatTy()) {
2468 bool Ignored;
2469 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2470 &Ignored);
2471 }
2472 V = ConstantFP::get(Context, ID.APFloatVal);
2473
2474 if (V->getType() != Ty)
2475 return Error(ID.Loc, "floating point constant does not have type '" +
2476 getTypeString(Ty) + "'");
2477
2478 return false;
2479 case ValID::t_Null:
2480 if (!Ty->isPointerTy())
2481 return Error(ID.Loc, "null must be a pointer type");
2482 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2483 return false;
2484 case ValID::t_Undef:
2485 // FIXME: LabelTy should not be a first-class type.
2486 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2487 return Error(ID.Loc, "invalid type for undef constant");
2488 V = UndefValue::get(Ty);
2489 return false;
2490 case ValID::t_EmptyArray:
2491 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2492 return Error(ID.Loc, "invalid empty array initializer");
2493 V = UndefValue::get(Ty);
2494 return false;
2495 case ValID::t_Zero:
2496 // FIXME: LabelTy should not be a first-class type.
2497 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2498 return Error(ID.Loc, "invalid type for null constant");
2499 V = Constant::getNullValue(Ty);
2500 return false;
2501 case ValID::t_Constant:
2502 if (ID.ConstantVal->getType() != Ty)
2503 return Error(ID.Loc, "constant expression type mismatch");
2504
2505 V = ID.ConstantVal;
2506 return false;
2507 case ValID::t_ConstantStruct:
2508 case ValID::t_PackedConstantStruct:
2509 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2510 if (ST->getNumElements() != ID.UIntVal)
2511 return Error(ID.Loc,
2512 "initializer with struct type has wrong # elements");
2513 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2514 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2515
2516 // Verify that the elements are compatible with the structtype.
2517 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2518 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2519 return Error(ID.Loc, "element " + Twine(i) +
2520 " of struct initializer doesn't match struct element type");
2521
2522 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2523 ID.UIntVal));
2524 } else
2525 return Error(ID.Loc, "constant expression type mismatch");
2526 return false;
2527 }
2528 }
2529
ParseValue(Type * Ty,Value * & V,PerFunctionState * PFS)2530 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2531 V = 0;
2532 ValID ID;
2533 return ParseValID(ID, PFS) ||
2534 ConvertValIDToValue(Ty, ID, V, PFS);
2535 }
2536
ParseTypeAndValue(Value * & V,PerFunctionState * PFS)2537 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2538 Type *Ty = 0;
2539 return ParseType(Ty) ||
2540 ParseValue(Ty, V, PFS);
2541 }
2542
ParseTypeAndBasicBlock(BasicBlock * & BB,LocTy & Loc,PerFunctionState & PFS)2543 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2544 PerFunctionState &PFS) {
2545 Value *V;
2546 Loc = Lex.getLoc();
2547 if (ParseTypeAndValue(V, PFS)) return true;
2548 if (!isa<BasicBlock>(V))
2549 return Error(Loc, "expected a basic block");
2550 BB = cast<BasicBlock>(V);
2551 return false;
2552 }
2553
2554
2555 /// FunctionHeader
2556 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2557 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2558 /// OptionalAlign OptGC
ParseFunctionHeader(Function * & Fn,bool isDefine)2559 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2560 // Parse the linkage.
2561 LocTy LinkageLoc = Lex.getLoc();
2562 unsigned Linkage;
2563
2564 unsigned Visibility, RetAttrs;
2565 CallingConv::ID CC;
2566 Type *RetType = 0;
2567 LocTy RetTypeLoc = Lex.getLoc();
2568 if (ParseOptionalLinkage(Linkage) ||
2569 ParseOptionalVisibility(Visibility) ||
2570 ParseOptionalCallingConv(CC) ||
2571 ParseOptionalAttrs(RetAttrs, 1) ||
2572 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2573 return true;
2574
2575 // Verify that the linkage is ok.
2576 switch ((GlobalValue::LinkageTypes)Linkage) {
2577 case GlobalValue::ExternalLinkage:
2578 break; // always ok.
2579 case GlobalValue::DLLImportLinkage:
2580 case GlobalValue::ExternalWeakLinkage:
2581 if (isDefine)
2582 return Error(LinkageLoc, "invalid linkage for function definition");
2583 break;
2584 case GlobalValue::PrivateLinkage:
2585 case GlobalValue::LinkerPrivateLinkage:
2586 case GlobalValue::LinkerPrivateWeakLinkage:
2587 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2588 case GlobalValue::InternalLinkage:
2589 case GlobalValue::AvailableExternallyLinkage:
2590 case GlobalValue::LinkOnceAnyLinkage:
2591 case GlobalValue::LinkOnceODRLinkage:
2592 case GlobalValue::WeakAnyLinkage:
2593 case GlobalValue::WeakODRLinkage:
2594 case GlobalValue::DLLExportLinkage:
2595 if (!isDefine)
2596 return Error(LinkageLoc, "invalid linkage for function declaration");
2597 break;
2598 case GlobalValue::AppendingLinkage:
2599 case GlobalValue::CommonLinkage:
2600 return Error(LinkageLoc, "invalid function linkage type");
2601 }
2602
2603 if (!FunctionType::isValidReturnType(RetType))
2604 return Error(RetTypeLoc, "invalid function return type");
2605
2606 LocTy NameLoc = Lex.getLoc();
2607
2608 std::string FunctionName;
2609 if (Lex.getKind() == lltok::GlobalVar) {
2610 FunctionName = Lex.getStrVal();
2611 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2612 unsigned NameID = Lex.getUIntVal();
2613
2614 if (NameID != NumberedVals.size())
2615 return TokError("function expected to be numbered '%" +
2616 Twine(NumberedVals.size()) + "'");
2617 } else {
2618 return TokError("expected function name");
2619 }
2620
2621 Lex.Lex();
2622
2623 if (Lex.getKind() != lltok::lparen)
2624 return TokError("expected '(' in function argument list");
2625
2626 SmallVector<ArgInfo, 8> ArgList;
2627 bool isVarArg;
2628 unsigned FuncAttrs;
2629 std::string Section;
2630 unsigned Alignment;
2631 std::string GC;
2632 bool UnnamedAddr;
2633 LocTy UnnamedAddrLoc;
2634
2635 if (ParseArgumentList(ArgList, isVarArg) ||
2636 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2637 &UnnamedAddrLoc) ||
2638 ParseOptionalAttrs(FuncAttrs, 2) ||
2639 (EatIfPresent(lltok::kw_section) &&
2640 ParseStringConstant(Section)) ||
2641 ParseOptionalAlignment(Alignment) ||
2642 (EatIfPresent(lltok::kw_gc) &&
2643 ParseStringConstant(GC)))
2644 return true;
2645
2646 // If the alignment was parsed as an attribute, move to the alignment field.
2647 if (FuncAttrs & Attribute::Alignment) {
2648 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2649 FuncAttrs &= ~Attribute::Alignment;
2650 }
2651
2652 // Okay, if we got here, the function is syntactically valid. Convert types
2653 // and do semantic checks.
2654 std::vector<Type*> ParamTypeList;
2655 SmallVector<AttributeWithIndex, 8> Attrs;
2656
2657 if (RetAttrs != Attribute::None)
2658 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2659
2660 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2661 ParamTypeList.push_back(ArgList[i].Ty);
2662 if (ArgList[i].Attrs != Attribute::None)
2663 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2664 }
2665
2666 if (FuncAttrs != Attribute::None)
2667 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2668
2669 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2670
2671 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2672 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2673
2674 FunctionType *FT =
2675 FunctionType::get(RetType, ParamTypeList, isVarArg);
2676 PointerType *PFT = PointerType::getUnqual(FT);
2677
2678 Fn = 0;
2679 if (!FunctionName.empty()) {
2680 // If this was a definition of a forward reference, remove the definition
2681 // from the forward reference table and fill in the forward ref.
2682 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2683 ForwardRefVals.find(FunctionName);
2684 if (FRVI != ForwardRefVals.end()) {
2685 Fn = M->getFunction(FunctionName);
2686 if (Fn->getType() != PFT)
2687 return Error(FRVI->second.second, "invalid forward reference to "
2688 "function '" + FunctionName + "' with wrong type!");
2689
2690 ForwardRefVals.erase(FRVI);
2691 } else if ((Fn = M->getFunction(FunctionName))) {
2692 // Reject redefinitions.
2693 return Error(NameLoc, "invalid redefinition of function '" +
2694 FunctionName + "'");
2695 } else if (M->getNamedValue(FunctionName)) {
2696 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2697 }
2698
2699 } else {
2700 // If this is a definition of a forward referenced function, make sure the
2701 // types agree.
2702 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2703 = ForwardRefValIDs.find(NumberedVals.size());
2704 if (I != ForwardRefValIDs.end()) {
2705 Fn = cast<Function>(I->second.first);
2706 if (Fn->getType() != PFT)
2707 return Error(NameLoc, "type of definition and forward reference of '@" +
2708 Twine(NumberedVals.size()) + "' disagree");
2709 ForwardRefValIDs.erase(I);
2710 }
2711 }
2712
2713 if (Fn == 0)
2714 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2715 else // Move the forward-reference to the correct spot in the module.
2716 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2717
2718 if (FunctionName.empty())
2719 NumberedVals.push_back(Fn);
2720
2721 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2722 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2723 Fn->setCallingConv(CC);
2724 Fn->setAttributes(PAL);
2725 Fn->setUnnamedAddr(UnnamedAddr);
2726 Fn->setAlignment(Alignment);
2727 Fn->setSection(Section);
2728 if (!GC.empty()) Fn->setGC(GC.c_str());
2729
2730 // Add all of the arguments we parsed to the function.
2731 Function::arg_iterator ArgIt = Fn->arg_begin();
2732 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2733 // If the argument has a name, insert it into the argument symbol table.
2734 if (ArgList[i].Name.empty()) continue;
2735
2736 // Set the name, if it conflicted, it will be auto-renamed.
2737 ArgIt->setName(ArgList[i].Name);
2738
2739 if (ArgIt->getName() != ArgList[i].Name)
2740 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2741 ArgList[i].Name + "'");
2742 }
2743
2744 return false;
2745 }
2746
2747
2748 /// ParseFunctionBody
2749 /// ::= '{' BasicBlock+ '}'
2750 ///
ParseFunctionBody(Function & Fn)2751 bool LLParser::ParseFunctionBody(Function &Fn) {
2752 if (Lex.getKind() != lltok::lbrace)
2753 return TokError("expected '{' in function body");
2754 Lex.Lex(); // eat the {.
2755
2756 int FunctionNumber = -1;
2757 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2758
2759 PerFunctionState PFS(*this, Fn, FunctionNumber);
2760
2761 // We need at least one basic block.
2762 if (Lex.getKind() == lltok::rbrace)
2763 return TokError("function body requires at least one basic block");
2764
2765 while (Lex.getKind() != lltok::rbrace)
2766 if (ParseBasicBlock(PFS)) return true;
2767
2768 // Eat the }.
2769 Lex.Lex();
2770
2771 // Verify function is ok.
2772 return PFS.FinishFunction();
2773 }
2774
2775 /// ParseBasicBlock
2776 /// ::= LabelStr? Instruction*
ParseBasicBlock(PerFunctionState & PFS)2777 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2778 // If this basic block starts out with a name, remember it.
2779 std::string Name;
2780 LocTy NameLoc = Lex.getLoc();
2781 if (Lex.getKind() == lltok::LabelStr) {
2782 Name = Lex.getStrVal();
2783 Lex.Lex();
2784 }
2785
2786 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2787 if (BB == 0) return true;
2788
2789 std::string NameStr;
2790
2791 // Parse the instructions in this block until we get a terminator.
2792 Instruction *Inst;
2793 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2794 do {
2795 // This instruction may have three possibilities for a name: a) none
2796 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2797 LocTy NameLoc = Lex.getLoc();
2798 int NameID = -1;
2799 NameStr = "";
2800
2801 if (Lex.getKind() == lltok::LocalVarID) {
2802 NameID = Lex.getUIntVal();
2803 Lex.Lex();
2804 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2805 return true;
2806 } else if (Lex.getKind() == lltok::LocalVar) {
2807 NameStr = Lex.getStrVal();
2808 Lex.Lex();
2809 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2810 return true;
2811 }
2812
2813 switch (ParseInstruction(Inst, BB, PFS)) {
2814 default: assert(0 && "Unknown ParseInstruction result!");
2815 case InstError: return true;
2816 case InstNormal:
2817 BB->getInstList().push_back(Inst);
2818
2819 // With a normal result, we check to see if the instruction is followed by
2820 // a comma and metadata.
2821 if (EatIfPresent(lltok::comma))
2822 if (ParseInstructionMetadata(Inst, &PFS))
2823 return true;
2824 break;
2825 case InstExtraComma:
2826 BB->getInstList().push_back(Inst);
2827
2828 // If the instruction parser ate an extra comma at the end of it, it
2829 // *must* be followed by metadata.
2830 if (ParseInstructionMetadata(Inst, &PFS))
2831 return true;
2832 break;
2833 }
2834
2835 // Set the name on the instruction.
2836 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2837 } while (!isa<TerminatorInst>(Inst));
2838
2839 return false;
2840 }
2841
2842 //===----------------------------------------------------------------------===//
2843 // Instruction Parsing.
2844 //===----------------------------------------------------------------------===//
2845
2846 /// ParseInstruction - Parse one of the many different instructions.
2847 ///
ParseInstruction(Instruction * & Inst,BasicBlock * BB,PerFunctionState & PFS)2848 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2849 PerFunctionState &PFS) {
2850 lltok::Kind Token = Lex.getKind();
2851 if (Token == lltok::Eof)
2852 return TokError("found end of file when expecting more instructions");
2853 LocTy Loc = Lex.getLoc();
2854 unsigned KeywordVal = Lex.getUIntVal();
2855 Lex.Lex(); // Eat the keyword.
2856
2857 switch (Token) {
2858 default: return Error(Loc, "expected instruction opcode");
2859 // Terminator Instructions.
2860 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2861 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2862 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2863 case lltok::kw_br: return ParseBr(Inst, PFS);
2864 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2865 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2866 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2867 // Binary Operators.
2868 case lltok::kw_add:
2869 case lltok::kw_sub:
2870 case lltok::kw_mul:
2871 case lltok::kw_shl: {
2872 bool NUW = EatIfPresent(lltok::kw_nuw);
2873 bool NSW = EatIfPresent(lltok::kw_nsw);
2874 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2875
2876 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2877
2878 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2879 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2880 return false;
2881 }
2882 case lltok::kw_fadd:
2883 case lltok::kw_fsub:
2884 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2885
2886 case lltok::kw_sdiv:
2887 case lltok::kw_udiv:
2888 case lltok::kw_lshr:
2889 case lltok::kw_ashr: {
2890 bool Exact = EatIfPresent(lltok::kw_exact);
2891
2892 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2893 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2894 return false;
2895 }
2896
2897 case lltok::kw_urem:
2898 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2899 case lltok::kw_fdiv:
2900 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2901 case lltok::kw_and:
2902 case lltok::kw_or:
2903 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2904 case lltok::kw_icmp:
2905 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2906 // Casts.
2907 case lltok::kw_trunc:
2908 case lltok::kw_zext:
2909 case lltok::kw_sext:
2910 case lltok::kw_fptrunc:
2911 case lltok::kw_fpext:
2912 case lltok::kw_bitcast:
2913 case lltok::kw_uitofp:
2914 case lltok::kw_sitofp:
2915 case lltok::kw_fptoui:
2916 case lltok::kw_fptosi:
2917 case lltok::kw_inttoptr:
2918 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2919 // Other.
2920 case lltok::kw_select: return ParseSelect(Inst, PFS);
2921 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2922 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2923 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2924 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2925 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2926 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2927 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2928 // Memory.
2929 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2930 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2931 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2932 case lltok::kw_volatile:
2933 if (EatIfPresent(lltok::kw_load))
2934 return ParseLoad(Inst, PFS, true);
2935 else if (EatIfPresent(lltok::kw_store))
2936 return ParseStore(Inst, PFS, true);
2937 else
2938 return TokError("expected 'load' or 'store'");
2939 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2940 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2941 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2942 }
2943 }
2944
2945 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
ParseCmpPredicate(unsigned & P,unsigned Opc)2946 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2947 if (Opc == Instruction::FCmp) {
2948 switch (Lex.getKind()) {
2949 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2950 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2951 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2952 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2953 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2954 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2955 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2956 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2957 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2958 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2959 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2960 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2961 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2962 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2963 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2964 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2965 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2966 }
2967 } else {
2968 switch (Lex.getKind()) {
2969 default: TokError("expected icmp predicate (e.g. 'eq')");
2970 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2971 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2972 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2973 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2974 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2975 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2976 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2977 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2978 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2979 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2980 }
2981 }
2982 Lex.Lex();
2983 return false;
2984 }
2985
2986 //===----------------------------------------------------------------------===//
2987 // Terminator Instructions.
2988 //===----------------------------------------------------------------------===//
2989
2990 /// ParseRet - Parse a return instruction.
2991 /// ::= 'ret' void (',' !dbg, !1)*
2992 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
ParseRet(Instruction * & Inst,BasicBlock * BB,PerFunctionState & PFS)2993 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2994 PerFunctionState &PFS) {
2995 SMLoc TypeLoc = Lex.getLoc();
2996 Type *Ty = 0;
2997 if (ParseType(Ty, true /*void allowed*/)) return true;
2998
2999 Type *ResType = PFS.getFunction().getReturnType();
3000
3001 if (Ty->isVoidTy()) {
3002 if (!ResType->isVoidTy())
3003 return Error(TypeLoc, "value doesn't match function result type '" +
3004 getTypeString(ResType) + "'");
3005
3006 Inst = ReturnInst::Create(Context);
3007 return false;
3008 }
3009
3010 Value *RV;
3011 if (ParseValue(Ty, RV, PFS)) return true;
3012
3013 if (ResType != RV->getType())
3014 return Error(TypeLoc, "value doesn't match function result type '" +
3015 getTypeString(ResType) + "'");
3016
3017 Inst = ReturnInst::Create(Context, RV);
3018 return false;
3019 }
3020
3021
3022 /// ParseBr
3023 /// ::= 'br' TypeAndValue
3024 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
ParseBr(Instruction * & Inst,PerFunctionState & PFS)3025 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3026 LocTy Loc, Loc2;
3027 Value *Op0;
3028 BasicBlock *Op1, *Op2;
3029 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3030
3031 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3032 Inst = BranchInst::Create(BB);
3033 return false;
3034 }
3035
3036 if (Op0->getType() != Type::getInt1Ty(Context))
3037 return Error(Loc, "branch condition must have 'i1' type");
3038
3039 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3040 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3041 ParseToken(lltok::comma, "expected ',' after true destination") ||
3042 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3043 return true;
3044
3045 Inst = BranchInst::Create(Op1, Op2, Op0);
3046 return false;
3047 }
3048
3049 /// ParseSwitch
3050 /// Instruction
3051 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3052 /// JumpTable
3053 /// ::= (TypeAndValue ',' TypeAndValue)*
ParseSwitch(Instruction * & Inst,PerFunctionState & PFS)3054 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3055 LocTy CondLoc, BBLoc;
3056 Value *Cond;
3057 BasicBlock *DefaultBB;
3058 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3059 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3060 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3061 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3062 return true;
3063
3064 if (!Cond->getType()->isIntegerTy())
3065 return Error(CondLoc, "switch condition must have integer type");
3066
3067 // Parse the jump table pairs.
3068 SmallPtrSet<Value*, 32> SeenCases;
3069 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3070 while (Lex.getKind() != lltok::rsquare) {
3071 Value *Constant;
3072 BasicBlock *DestBB;
3073
3074 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3075 ParseToken(lltok::comma, "expected ',' after case value") ||
3076 ParseTypeAndBasicBlock(DestBB, PFS))
3077 return true;
3078
3079 if (!SeenCases.insert(Constant))
3080 return Error(CondLoc, "duplicate case value in switch");
3081 if (!isa<ConstantInt>(Constant))
3082 return Error(CondLoc, "case value is not a constant integer");
3083
3084 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3085 }
3086
3087 Lex.Lex(); // Eat the ']'.
3088
3089 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3090 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3091 SI->addCase(Table[i].first, Table[i].second);
3092 Inst = SI;
3093 return false;
3094 }
3095
3096 /// ParseIndirectBr
3097 /// Instruction
3098 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
ParseIndirectBr(Instruction * & Inst,PerFunctionState & PFS)3099 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3100 LocTy AddrLoc;
3101 Value *Address;
3102 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3103 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3104 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3105 return true;
3106
3107 if (!Address->getType()->isPointerTy())
3108 return Error(AddrLoc, "indirectbr address must have pointer type");
3109
3110 // Parse the destination list.
3111 SmallVector<BasicBlock*, 16> DestList;
3112
3113 if (Lex.getKind() != lltok::rsquare) {
3114 BasicBlock *DestBB;
3115 if (ParseTypeAndBasicBlock(DestBB, PFS))
3116 return true;
3117 DestList.push_back(DestBB);
3118
3119 while (EatIfPresent(lltok::comma)) {
3120 if (ParseTypeAndBasicBlock(DestBB, PFS))
3121 return true;
3122 DestList.push_back(DestBB);
3123 }
3124 }
3125
3126 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3127 return true;
3128
3129 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3130 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3131 IBI->addDestination(DestList[i]);
3132 Inst = IBI;
3133 return false;
3134 }
3135
3136
3137 /// ParseInvoke
3138 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3139 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
ParseInvoke(Instruction * & Inst,PerFunctionState & PFS)3140 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3141 LocTy CallLoc = Lex.getLoc();
3142 unsigned RetAttrs, FnAttrs;
3143 CallingConv::ID CC;
3144 Type *RetType = 0;
3145 LocTy RetTypeLoc;
3146 ValID CalleeID;
3147 SmallVector<ParamInfo, 16> ArgList;
3148
3149 BasicBlock *NormalBB, *UnwindBB;
3150 if (ParseOptionalCallingConv(CC) ||
3151 ParseOptionalAttrs(RetAttrs, 1) ||
3152 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3153 ParseValID(CalleeID) ||
3154 ParseParameterList(ArgList, PFS) ||
3155 ParseOptionalAttrs(FnAttrs, 2) ||
3156 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3157 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3158 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3159 ParseTypeAndBasicBlock(UnwindBB, PFS))
3160 return true;
3161
3162 // If RetType is a non-function pointer type, then this is the short syntax
3163 // for the call, which means that RetType is just the return type. Infer the
3164 // rest of the function argument types from the arguments that are present.
3165 PointerType *PFTy = 0;
3166 FunctionType *Ty = 0;
3167 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3168 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3169 // Pull out the types of all of the arguments...
3170 std::vector<Type*> ParamTypes;
3171 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3172 ParamTypes.push_back(ArgList[i].V->getType());
3173
3174 if (!FunctionType::isValidReturnType(RetType))
3175 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3176
3177 Ty = FunctionType::get(RetType, ParamTypes, false);
3178 PFTy = PointerType::getUnqual(Ty);
3179 }
3180
3181 // Look up the callee.
3182 Value *Callee;
3183 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3184
3185 // Set up the Attributes for the function.
3186 SmallVector<AttributeWithIndex, 8> Attrs;
3187 if (RetAttrs != Attribute::None)
3188 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3189
3190 SmallVector<Value*, 8> Args;
3191
3192 // Loop through FunctionType's arguments and ensure they are specified
3193 // correctly. Also, gather any parameter attributes.
3194 FunctionType::param_iterator I = Ty->param_begin();
3195 FunctionType::param_iterator E = Ty->param_end();
3196 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3197 Type *ExpectedTy = 0;
3198 if (I != E) {
3199 ExpectedTy = *I++;
3200 } else if (!Ty->isVarArg()) {
3201 return Error(ArgList[i].Loc, "too many arguments specified");
3202 }
3203
3204 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3205 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3206 getTypeString(ExpectedTy) + "'");
3207 Args.push_back(ArgList[i].V);
3208 if (ArgList[i].Attrs != Attribute::None)
3209 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3210 }
3211
3212 if (I != E)
3213 return Error(CallLoc, "not enough parameters specified for call");
3214
3215 if (FnAttrs != Attribute::None)
3216 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3217
3218 // Finish off the Attributes and check them
3219 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3220
3221 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3222 II->setCallingConv(CC);
3223 II->setAttributes(PAL);
3224 Inst = II;
3225 return false;
3226 }
3227
3228
3229
3230 //===----------------------------------------------------------------------===//
3231 // Binary Operators.
3232 //===----------------------------------------------------------------------===//
3233
3234 /// ParseArithmetic
3235 /// ::= ArithmeticOps TypeAndValue ',' Value
3236 ///
3237 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3238 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
ParseArithmetic(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc,unsigned OperandType)3239 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3240 unsigned Opc, unsigned OperandType) {
3241 LocTy Loc; Value *LHS, *RHS;
3242 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3243 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3244 ParseValue(LHS->getType(), RHS, PFS))
3245 return true;
3246
3247 bool Valid;
3248 switch (OperandType) {
3249 default: llvm_unreachable("Unknown operand type!");
3250 case 0: // int or FP.
3251 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3252 LHS->getType()->isFPOrFPVectorTy();
3253 break;
3254 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3255 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3256 }
3257
3258 if (!Valid)
3259 return Error(Loc, "invalid operand type for instruction");
3260
3261 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3262 return false;
3263 }
3264
3265 /// ParseLogical
3266 /// ::= ArithmeticOps TypeAndValue ',' Value {
ParseLogical(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)3267 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3268 unsigned Opc) {
3269 LocTy Loc; Value *LHS, *RHS;
3270 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3271 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3272 ParseValue(LHS->getType(), RHS, PFS))
3273 return true;
3274
3275 if (!LHS->getType()->isIntOrIntVectorTy())
3276 return Error(Loc,"instruction requires integer or integer vector operands");
3277
3278 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3279 return false;
3280 }
3281
3282
3283 /// ParseCompare
3284 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3285 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
ParseCompare(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)3286 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3287 unsigned Opc) {
3288 // Parse the integer/fp comparison predicate.
3289 LocTy Loc;
3290 unsigned Pred;
3291 Value *LHS, *RHS;
3292 if (ParseCmpPredicate(Pred, Opc) ||
3293 ParseTypeAndValue(LHS, Loc, PFS) ||
3294 ParseToken(lltok::comma, "expected ',' after compare value") ||
3295 ParseValue(LHS->getType(), RHS, PFS))
3296 return true;
3297
3298 if (Opc == Instruction::FCmp) {
3299 if (!LHS->getType()->isFPOrFPVectorTy())
3300 return Error(Loc, "fcmp requires floating point operands");
3301 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3302 } else {
3303 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3304 if (!LHS->getType()->isIntOrIntVectorTy() &&
3305 !LHS->getType()->isPointerTy())
3306 return Error(Loc, "icmp requires integer operands");
3307 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3308 }
3309 return false;
3310 }
3311
3312 //===----------------------------------------------------------------------===//
3313 // Other Instructions.
3314 //===----------------------------------------------------------------------===//
3315
3316
3317 /// ParseCast
3318 /// ::= CastOpc TypeAndValue 'to' Type
ParseCast(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)3319 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3320 unsigned Opc) {
3321 LocTy Loc;
3322 Value *Op;
3323 Type *DestTy = 0;
3324 if (ParseTypeAndValue(Op, Loc, PFS) ||
3325 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3326 ParseType(DestTy))
3327 return true;
3328
3329 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3330 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3331 return Error(Loc, "invalid cast opcode for cast from '" +
3332 getTypeString(Op->getType()) + "' to '" +
3333 getTypeString(DestTy) + "'");
3334 }
3335 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3336 return false;
3337 }
3338
3339 /// ParseSelect
3340 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
ParseSelect(Instruction * & Inst,PerFunctionState & PFS)3341 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3342 LocTy Loc;
3343 Value *Op0, *Op1, *Op2;
3344 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3345 ParseToken(lltok::comma, "expected ',' after select condition") ||
3346 ParseTypeAndValue(Op1, PFS) ||
3347 ParseToken(lltok::comma, "expected ',' after select value") ||
3348 ParseTypeAndValue(Op2, PFS))
3349 return true;
3350
3351 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3352 return Error(Loc, Reason);
3353
3354 Inst = SelectInst::Create(Op0, Op1, Op2);
3355 return false;
3356 }
3357
3358 /// ParseVA_Arg
3359 /// ::= 'va_arg' TypeAndValue ',' Type
ParseVA_Arg(Instruction * & Inst,PerFunctionState & PFS)3360 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3361 Value *Op;
3362 Type *EltTy = 0;
3363 LocTy TypeLoc;
3364 if (ParseTypeAndValue(Op, PFS) ||
3365 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3366 ParseType(EltTy, TypeLoc))
3367 return true;
3368
3369 if (!EltTy->isFirstClassType())
3370 return Error(TypeLoc, "va_arg requires operand with first class type");
3371
3372 Inst = new VAArgInst(Op, EltTy);
3373 return false;
3374 }
3375
3376 /// ParseExtractElement
3377 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
ParseExtractElement(Instruction * & Inst,PerFunctionState & PFS)3378 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3379 LocTy Loc;
3380 Value *Op0, *Op1;
3381 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3382 ParseToken(lltok::comma, "expected ',' after extract value") ||
3383 ParseTypeAndValue(Op1, PFS))
3384 return true;
3385
3386 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3387 return Error(Loc, "invalid extractelement operands");
3388
3389 Inst = ExtractElementInst::Create(Op0, Op1);
3390 return false;
3391 }
3392
3393 /// ParseInsertElement
3394 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
ParseInsertElement(Instruction * & Inst,PerFunctionState & PFS)3395 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3396 LocTy Loc;
3397 Value *Op0, *Op1, *Op2;
3398 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3399 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3400 ParseTypeAndValue(Op1, PFS) ||
3401 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3402 ParseTypeAndValue(Op2, PFS))
3403 return true;
3404
3405 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3406 return Error(Loc, "invalid insertelement operands");
3407
3408 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3409 return false;
3410 }
3411
3412 /// ParseShuffleVector
3413 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
ParseShuffleVector(Instruction * & Inst,PerFunctionState & PFS)3414 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3415 LocTy Loc;
3416 Value *Op0, *Op1, *Op2;
3417 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3418 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3419 ParseTypeAndValue(Op1, PFS) ||
3420 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3421 ParseTypeAndValue(Op2, PFS))
3422 return true;
3423
3424 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3425 return Error(Loc, "invalid extractelement operands");
3426
3427 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3428 return false;
3429 }
3430
3431 /// ParsePHI
3432 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
ParsePHI(Instruction * & Inst,PerFunctionState & PFS)3433 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3434 Type *Ty = 0; LocTy TypeLoc;
3435 Value *Op0, *Op1;
3436
3437 if (ParseType(Ty, TypeLoc) ||
3438 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3439 ParseValue(Ty, Op0, PFS) ||
3440 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3441 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3442 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3443 return true;
3444
3445 bool AteExtraComma = false;
3446 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3447 while (1) {
3448 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3449
3450 if (!EatIfPresent(lltok::comma))
3451 break;
3452
3453 if (Lex.getKind() == lltok::MetadataVar) {
3454 AteExtraComma = true;
3455 break;
3456 }
3457
3458 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3459 ParseValue(Ty, Op0, PFS) ||
3460 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3461 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3462 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3463 return true;
3464 }
3465
3466 if (!Ty->isFirstClassType())
3467 return Error(TypeLoc, "phi node must have first class type");
3468
3469 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3470 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3471 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3472 Inst = PN;
3473 return AteExtraComma ? InstExtraComma : InstNormal;
3474 }
3475
3476 /// ParseCall
3477 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3478 /// ParameterList OptionalAttrs
ParseCall(Instruction * & Inst,PerFunctionState & PFS,bool isTail)3479 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3480 bool isTail) {
3481 unsigned RetAttrs, FnAttrs;
3482 CallingConv::ID CC;
3483 Type *RetType = 0;
3484 LocTy RetTypeLoc;
3485 ValID CalleeID;
3486 SmallVector<ParamInfo, 16> ArgList;
3487 LocTy CallLoc = Lex.getLoc();
3488
3489 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3490 ParseOptionalCallingConv(CC) ||
3491 ParseOptionalAttrs(RetAttrs, 1) ||
3492 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3493 ParseValID(CalleeID) ||
3494 ParseParameterList(ArgList, PFS) ||
3495 ParseOptionalAttrs(FnAttrs, 2))
3496 return true;
3497
3498 // If RetType is a non-function pointer type, then this is the short syntax
3499 // for the call, which means that RetType is just the return type. Infer the
3500 // rest of the function argument types from the arguments that are present.
3501 PointerType *PFTy = 0;
3502 FunctionType *Ty = 0;
3503 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3504 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3505 // Pull out the types of all of the arguments...
3506 std::vector<Type*> ParamTypes;
3507 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3508 ParamTypes.push_back(ArgList[i].V->getType());
3509
3510 if (!FunctionType::isValidReturnType(RetType))
3511 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3512
3513 Ty = FunctionType::get(RetType, ParamTypes, false);
3514 PFTy = PointerType::getUnqual(Ty);
3515 }
3516
3517 // Look up the callee.
3518 Value *Callee;
3519 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3520
3521 // Set up the Attributes for the function.
3522 SmallVector<AttributeWithIndex, 8> Attrs;
3523 if (RetAttrs != Attribute::None)
3524 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3525
3526 SmallVector<Value*, 8> Args;
3527
3528 // Loop through FunctionType's arguments and ensure they are specified
3529 // correctly. Also, gather any parameter attributes.
3530 FunctionType::param_iterator I = Ty->param_begin();
3531 FunctionType::param_iterator E = Ty->param_end();
3532 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3533 Type *ExpectedTy = 0;
3534 if (I != E) {
3535 ExpectedTy = *I++;
3536 } else if (!Ty->isVarArg()) {
3537 return Error(ArgList[i].Loc, "too many arguments specified");
3538 }
3539
3540 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3541 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3542 getTypeString(ExpectedTy) + "'");
3543 Args.push_back(ArgList[i].V);
3544 if (ArgList[i].Attrs != Attribute::None)
3545 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3546 }
3547
3548 if (I != E)
3549 return Error(CallLoc, "not enough parameters specified for call");
3550
3551 if (FnAttrs != Attribute::None)
3552 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3553
3554 // Finish off the Attributes and check them
3555 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3556
3557 CallInst *CI = CallInst::Create(Callee, Args);
3558 CI->setTailCall(isTail);
3559 CI->setCallingConv(CC);
3560 CI->setAttributes(PAL);
3561 Inst = CI;
3562 return false;
3563 }
3564
3565 //===----------------------------------------------------------------------===//
3566 // Memory Instructions.
3567 //===----------------------------------------------------------------------===//
3568
3569 /// ParseAlloc
3570 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
ParseAlloc(Instruction * & Inst,PerFunctionState & PFS)3571 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3572 Value *Size = 0;
3573 LocTy SizeLoc;
3574 unsigned Alignment = 0;
3575 Type *Ty = 0;
3576 if (ParseType(Ty)) return true;
3577
3578 bool AteExtraComma = false;
3579 if (EatIfPresent(lltok::comma)) {
3580 if (Lex.getKind() == lltok::kw_align) {
3581 if (ParseOptionalAlignment(Alignment)) return true;
3582 } else if (Lex.getKind() == lltok::MetadataVar) {
3583 AteExtraComma = true;
3584 } else {
3585 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3586 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3587 return true;
3588 }
3589 }
3590
3591 if (Size && !Size->getType()->isIntegerTy())
3592 return Error(SizeLoc, "element count must have integer type");
3593
3594 Inst = new AllocaInst(Ty, Size, Alignment);
3595 return AteExtraComma ? InstExtraComma : InstNormal;
3596 }
3597
3598 /// ParseLoad
3599 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
ParseLoad(Instruction * & Inst,PerFunctionState & PFS,bool isVolatile)3600 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3601 bool isVolatile) {
3602 Value *Val; LocTy Loc;
3603 unsigned Alignment = 0;
3604 bool AteExtraComma = false;
3605 if (ParseTypeAndValue(Val, Loc, PFS) ||
3606 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3607 return true;
3608
3609 if (!Val->getType()->isPointerTy() ||
3610 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3611 return Error(Loc, "load operand must be a pointer to a first class type");
3612
3613 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3614 return AteExtraComma ? InstExtraComma : InstNormal;
3615 }
3616
3617 /// ParseStore
3618 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
ParseStore(Instruction * & Inst,PerFunctionState & PFS,bool isVolatile)3619 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3620 bool isVolatile) {
3621 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3622 unsigned Alignment = 0;
3623 bool AteExtraComma = false;
3624 if (ParseTypeAndValue(Val, Loc, PFS) ||
3625 ParseToken(lltok::comma, "expected ',' after store operand") ||
3626 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3627 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3628 return true;
3629
3630 if (!Ptr->getType()->isPointerTy())
3631 return Error(PtrLoc, "store operand must be a pointer");
3632 if (!Val->getType()->isFirstClassType())
3633 return Error(Loc, "store operand must be a first class value");
3634 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3635 return Error(Loc, "stored value and pointer type do not match");
3636
3637 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3638 return AteExtraComma ? InstExtraComma : InstNormal;
3639 }
3640
3641 /// ParseGetElementPtr
3642 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
ParseGetElementPtr(Instruction * & Inst,PerFunctionState & PFS)3643 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3644 Value *Ptr, *Val; LocTy Loc, EltLoc;
3645
3646 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3647
3648 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3649
3650 if (!Ptr->getType()->isPointerTy())
3651 return Error(Loc, "base of getelementptr must be a pointer");
3652
3653 SmallVector<Value*, 16> Indices;
3654 bool AteExtraComma = false;
3655 while (EatIfPresent(lltok::comma)) {
3656 if (Lex.getKind() == lltok::MetadataVar) {
3657 AteExtraComma = true;
3658 break;
3659 }
3660 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3661 if (!Val->getType()->isIntegerTy())
3662 return Error(EltLoc, "getelementptr index must be an integer");
3663 Indices.push_back(Val);
3664 }
3665
3666 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3667 Indices.begin(), Indices.end()))
3668 return Error(Loc, "invalid getelementptr indices");
3669 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3670 if (InBounds)
3671 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3672 return AteExtraComma ? InstExtraComma : InstNormal;
3673 }
3674
3675 /// ParseExtractValue
3676 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
ParseExtractValue(Instruction * & Inst,PerFunctionState & PFS)3677 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3678 Value *Val; LocTy Loc;
3679 SmallVector<unsigned, 4> Indices;
3680 bool AteExtraComma;
3681 if (ParseTypeAndValue(Val, Loc, PFS) ||
3682 ParseIndexList(Indices, AteExtraComma))
3683 return true;
3684
3685 if (!Val->getType()->isAggregateType())
3686 return Error(Loc, "extractvalue operand must be aggregate type");
3687
3688 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3689 return Error(Loc, "invalid indices for extractvalue");
3690 Inst = ExtractValueInst::Create(Val, Indices);
3691 return AteExtraComma ? InstExtraComma : InstNormal;
3692 }
3693
3694 /// ParseInsertValue
3695 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
ParseInsertValue(Instruction * & Inst,PerFunctionState & PFS)3696 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3697 Value *Val0, *Val1; LocTy Loc0, Loc1;
3698 SmallVector<unsigned, 4> Indices;
3699 bool AteExtraComma;
3700 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3701 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3702 ParseTypeAndValue(Val1, Loc1, PFS) ||
3703 ParseIndexList(Indices, AteExtraComma))
3704 return true;
3705
3706 if (!Val0->getType()->isAggregateType())
3707 return Error(Loc0, "insertvalue operand must be aggregate type");
3708
3709 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
3710 return Error(Loc0, "invalid indices for insertvalue");
3711 Inst = InsertValueInst::Create(Val0, Val1, Indices);
3712 return AteExtraComma ? InstExtraComma : InstNormal;
3713 }
3714
3715 //===----------------------------------------------------------------------===//
3716 // Embedded metadata.
3717 //===----------------------------------------------------------------------===//
3718
3719 /// ParseMDNodeVector
3720 /// ::= Element (',' Element)*
3721 /// Element
3722 /// ::= 'null' | TypeAndValue
ParseMDNodeVector(SmallVectorImpl<Value * > & Elts,PerFunctionState * PFS)3723 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3724 PerFunctionState *PFS) {
3725 // Check for an empty list.
3726 if (Lex.getKind() == lltok::rbrace)
3727 return false;
3728
3729 do {
3730 // Null is a special case since it is typeless.
3731 if (EatIfPresent(lltok::kw_null)) {
3732 Elts.push_back(0);
3733 continue;
3734 }
3735
3736 Value *V = 0;
3737 if (ParseTypeAndValue(V, PFS)) return true;
3738 Elts.push_back(V);
3739 } while (EatIfPresent(lltok::comma));
3740
3741 return false;
3742 }
3743